/**
 * Created by guo.xiaomin on 2017-09-21.
 */
var async = require('async');
var moment = require('moment');
var schedule = require("node-schedule");
var messageUtil = require('../common/utils/messageUtil');
var toolUtil = require('../common/utils/toolUtil');
var mtOrder = mongoose.model('mtOrder');
var User = mongoose.model('user');
var Regions = mongoose.model('masterData_Regions');
var Community = mongoose.model('community');
var userService = require('./userService');
/*  宝宝树66小区sprint4    mod   66后台结算佣金管理.计算佣金比例 guoxiaomin  20171101  start   */
var userInvitation = mongoose.model('user_invitation');
var mtOrderCheckLog = mongoose.model('mtOrderCheckLog');
var mtOrderActuaryLog = mongoose.model('mtOrderActuaryLog');
var RoleApply = mongoose.model('user_role_apply');
/*  宝宝树66小区sprint4    mod   66后台结算佣金管理.计算佣金比例 guoxiaomin  20171101  end   */

var refundStatusFor66 = mongoose.model('refundStatusFor66');

var mtOrderBalance = mongoose.model('mtOrderBalance');

exports.mtOrderSchedule = function (callback) {
    // 服务器启动/重启的时候执行一次
    var readyTime = moment().format('YYYY-MM-DD HH:mm:ss');
    logger.info('mtOrderSchedule ready at: ' + readyTime);

    var rule = new schedule.RecurrenceRule();
    rule.hour = mtOrderScheduleHour;
    rule.minute = mtOrderScheduleMinute;
    logger.info('mtOrderSchedule将会在每天的' + mtOrderScheduleHour + '点' + mtOrderScheduleMinute + '分执行!');

    // 测试用
    // var startDateSelect = '2017-08-30';
    // var endDateSelect = '2017-08-30';
    // var today = new Date(moment(startDateSelect, "YYYY-MM-DD").format());
    // var yesterday = new Date(moment(startDateSelect, "YYYY-MM-DD").subtract(1, "days").format("YYYY-MM-DD"));

    var orderSchedule = schedule.scheduleJob(rule, function(){
        var everyDayOnceTime = moment().format('YYYY-MM-DD hh:mm:ss');
        logger.info('mtOrderSchedule今天执行开始时间为: ' + everyDayOnceTime);

        var today = new Date(moment(moment().format('YYYY-MM-DD')).subtract(1, "seconds").format("YYYY-MM-DD hh:mm:ss a"));
        var yesterday = new Date(moment(moment().format('YYYY-MM-DD')).subtract(1, "days").format("YYYY-MM-DD hh:mm:ss a"));
        logger.info('自动同步订单时间范围，exports.getMtOrderByStartEndDate参数为: ' + moment(yesterday).format('YYYY-MM-DD HH:mm:ss') + ',' + moment(today).format('YYYY-MM-DD HH:mm:ss'));

        // 旧版-start
        // exports.getMtOrderByStartEndDate(yesterday.getTime(), today.getTime(), yesterday, today, function(err, totalCount) {
        //     if(err) {
        //         logger.info('同步失败...' + err);
        //     } else {
        //         logger.info('成功执行件数...' + totalCount);
        //     }
        // });
        // 旧版-end

        var days = actuaryBeforeDays;
        logger.info('当天的前多少天精算的前1天为精算:' + days);
        // 粗算期间
        var beforeNstartDate = moment(moment().format('YYYY-MM-DD')).subtract(days, "days").format("YYYY-MM-DD");
        var beforeNendDate = moment(moment().format('YYYY-MM-DD')).subtract(1, "days").format("YYYY-MM-DD");
        logger.info('粗算订单时间范围，exports.actuaryByStartEndDate参数为: ' + moment(beforeNstartDate).format('YYYY-MM-DD HH:mm:ss') + ',' + moment(beforeNendDate).format('YYYY-MM-DD HH:mm:ss'));

        // 前75天数据(不会在变化)进行复核+精算
        var dayBeforeNend = new Date(moment(moment().format('YYYY-MM-DD')).subtract(days, "days").subtract(1, "seconds").format("YYYY-MM-DD hh:mm:ss a"));
        var dayBeforeNstart = new Date(moment(moment().format('YYYY-MM-DD')).subtract(days + 1, "days").format("YYYY-MM-DD hh:mm:ss a"));
        logger.info('复核+精算订单时间范围，exports.getMtOrderByStartEndDate和actuaryByStartEndDate参数为: ' + moment(dayBeforeNstart).format('YYYY-MM-DD HH:mm:ss') + ',' + moment(dayBeforeNend).format('YYYY-MM-DD HH:mm:ss'));
        // 新版-start
        async.series([
            function(callbackInner) {
                // 同步数据
                exports.getMtOrderByStartEndDate(yesterday.getTime(), today.getTime(), yesterday, today, 1, null, null, function(err, totalCount) {
                    if(err) {
                        logger.info('同步失败...' + err);
                        callbackInner(null, "error");
                    } else {
                        logger.info('同步成功执行件数...' + totalCount);
                        callbackInner(null, "success");
                    }
                });
            },
            function(callbackInner) {
                // 最近N-1天数据(可能会变化)进行粗算
                var dateArray = toolUtil.getArrayDateByStartEndDateMin(beforeNstartDate, beforeNendDate);
                exports.getNextVersionByDbName("mt_order_actuary_log", function(err, version) {
                    async.eachSeries(dateArray, function (temp, callbackInner2) {
                        var startTemp = new Date(moment(temp, "YYYY-MM-DD").format("YYYY-MM-DD HH:mm:ss"));
                        var endTemp = new Date(moment(temp, "YYYY-MM-DD").add(1, "days").subtract(1, "seconds").format("YYYY-MM-DD HH:mm:ss"));
                        logger.info("粗算开始..." + startTemp + "@" + endTemp);
                        exports.actuaryByStartEndDate(startTemp, endTemp, 1, version, true, function (err, status) {
                            logger.info("粗算结束..." + startTemp + "@" + endTemp);
                            callbackInner2(false);
                        });
                    }, function (err, result) {
                        callbackInner(null, '粗算成功');
                    });
                });
            },
            function(callbackInner) {
                // 前15天数据(不会在变化)进行复核
                exports.getNextVersionByDbName("mt_order_check_log", function(err, version){
                    exports.getMtOrderByStartEndDate(dayBeforeNstart.getTime(), dayBeforeNend.getTime(), dayBeforeNstart, dayBeforeNend, 2, version, true, function(err, totalCount) {
                        if(err) {
                            logger.info('复核失败...' + err);
                            callbackInner(null, "error");
                        } else {
                            logger.info('复核成功执行件数...' + totalCount);
                            callbackInner(null, "success");
                        }
                    });
                });
            },
            function(callbackInner) {
                // 66订单退款状态
                exports.refundStatusFor66OneDay(dayBeforeNstart, dayBeforeNend, function(err, totalCount) {
                    if(err) {
                        logger.info('同步退款信息失败...' + err);
                        callbackInner(null, "error");
                    } else {
                        logger.info('同步退款信息成功执行件数...' + totalCount);
                        callbackInner(null, "success");
                    }
                });
            },
            function(callbackInner) {
                logger.info("精算开始..." + dayBeforeNstart + "@" + dayBeforeNend);
                exports.isCheckErrorByStartEndDate(dayBeforeNstart, dayBeforeNend, function (err, flag) {
                    if(!flag) {
                        logger.info("复核没有错误，进行精算处理...");
                        exports.getNextVersionByDbName("mt_order_actuary_log", function(err, version) {
                            exports.actuaryByStartEndDate(dayBeforeNstart, dayBeforeNend, 2, version, true, function (err, status) {
                                logger.info("精算结束..." + dayBeforeNstart + "@" + dayBeforeNend);
                                callbackInner(null, '精算成功');
                            });
                        });
                    } else {
                        logger.error("复核有错，未进行精算...");
                        callbackInner(null, '未进行精算');
                    }
                });
            }
        ], function(err, result) {
            callback(err, result);
        });
        // 新版-end

    });
    callback(null, 'OK');
};

/*  宝宝树66小区五次改造-66订单退款状态    add   guo.xiaomin  20171120   start   */
// 66订单列表
// http://space.dayin.com/pages/viewpage.action?pageId=9886402

// 66订单退款状态
// http://space.dayin.com/pages/viewpage.action?pageId=11277850
// list:订单号列表,最多100个
exports.refundStatusFor66 = function(list, callback) {
    var mtUrl = refundStatusFor66Url;
    var param = '?platform=8&signature=none&timestamp=' + moment().format('YYYYMMDDhhmmss');
    var signtime = new Date().getTime(); // 签名时间
    var params = toolUtil.getRefundStatusSignParams(list, signtime);
    var finalUrl = mtUrl + param + params;
    logger.debug(finalUrl);
    restClient.get(finalUrl, function (tempData, response) {
        var statusCode = response.statusCode;
        logger.info('取得美囤66订单退款状态返回状态值:' + statusCode);
        if (statusCode == 200 && tempData != null && tempData != 'unknown') {
            // 美囤上线后使用
            var returnData = JSON.parse(tempData);
            var rtn_code = returnData.rtn_code;
            logger.info('rtn_code:' + rtn_code);
            if(rtn_code == '0') {
                logger.info('rtn_code=0');
                var data = returnData.data;
                if(data && data.length > 0) {
                    var length = data.length;
                    logger.info("本次退款数据件数为..." + length);
                    async.eachSeries(data, function (row, callbackInner) {
                        logger.debug(row);
                        var code = row.code; // 订单编号
                        var refundNo = row.refundNo; //退款单编号
                        var tempCreateTime = row.createTime; // 退款单创建时间
                        var refundStatus = row.refundStatus; // 退款状态1-等待打款 2-退款中 3-退款成功 4-退款失败 5-取消退款 6-更换账号退款中 7-更换账号退款成功 8-等待提交
                        var tempRefundTime = row.refundTime; // 退款单创建时间
                        var refundType = row.refundType; // 退款类型 1-取消订单 2-退货 3-重复支付 4-重复支付-手动生成
                        var mtOrderStatus = 0;
                        if(refundType == 1) {
                            // 取消订单
                            mtOrderStatus = 0;
                        } else if(refundType == 2) {
                            // 退货
                            mtOrderStatus = 100;
                        }
                        var refundAmount = row.refundAmount; // 退款金额
                        //退货信息start, 只有refundType=2时才有退货信息,否则为null
                        var rejectNo = null;// 退货单No
                        if(row.rejectNo) {
                            rejectNo = row.rejectNo;
                        }
                        var rejectSku = null; // 退货sku
                        if(row.rejectSku) {
                            rejectSku = row.rejectSku;
                        }
                        var refundQuantity = null;// 退货数量
                        if(row.refundQuantity) {
                            refundQuantity = row.refundQuantity;
                        }
                        var itemQuantity = null;// 商品购买数量
                        if(row.itemQuantity) {
                            itemQuantity = row.itemQuantity;
                        }
                        var refundAmountSku = null;// 退款金额 同主记录refundAmount
                        if(row.refundAmountSku) {
                            refundAmountSku = row.refundAmountSku;
                        }
                        //退货信息end

                        var mtOrderOption = {"order_id" : code};
                        var option = {"code" : code};
                        if(rejectSku) {
                            option.rejectSku = rejectSku;
                            mtOrderOption.sku_code = rejectSku;
                        }

                        mtOrder.update(mtOrderOption, {"status" : mtOrderStatus}).exec(function (mtOrderUpdateErr, mtOrderUpdateResult) {
                            if(mtOrderUpdateErr) {
                                logger.error("mtOrder.update error...");
                                logger.error(mtOrderOption);
                                callbackInner(false);
                            } else {
                                logger.info("mtOrder.update success...");
                                refundStatusFor66.findOne(option, function (err, tempReturnData) {
                                    if (tempReturnData) {
                                        logger.debug("update start code rejectSku..." + code + "@" + rejectSku);
                                        // update 更新
                                        var temp = {};
                                        temp.code = code;
                                        temp.refundNo = refundNo;
                                        temp.createTime = moment(new Date(tempCreateTime)).format("YYYY-MM-DD HH:mm:ss");
                                        temp.refundStatus = refundStatus;
                                        temp.refundTime = moment(new Date(tempRefundTime)).format("YYYY-MM-DD HH:mm:ss");
                                        temp.refundType = refundType;
                                        temp.refundAmount = refundAmount;
                                        temp.rejectNo = rejectNo;
                                        temp.rejectSku = rejectSku;
                                        temp.refundQuantity = refundQuantity;
                                        temp.itemQuantity = itemQuantity;
                                        temp.refundAmountSku = refundAmountSku;
                                        temp.dateLastModified = new Date();
                                        refundStatusFor66.update(option, temp).exec(function (updateErr, updateResult) {
                                            if(updateErr) {
                                                logger.error("update error code rejectSku..." + code + "@" + rejectSku);
                                                callbackInner(false);
                                            } else {
                                                logger.debug("update success code rejectSku..." + code + "@" + rejectSku);
                                                callbackInner(false);
                                            }
                                        });
                                    } else {
                                        logger.debug("insert start code rejectSku..." + code + "@" + rejectSku);
                                        // insert 新增
                                        var temp = new refundStatusFor66();
                                        temp.code = code;
                                        temp.refundNo = refundNo;
                                        temp.createTime = moment(new Date(tempCreateTime)).format("YYYY-MM-DD HH:mm:ss");
                                        temp.refundStatus = refundStatus;
                                        temp.refundTime = moment(new Date(tempRefundTime)).format("YYYY-MM-DD HH:mm:ss");
                                        temp.refundType = refundType;
                                        temp.refundAmount = refundAmount;
                                        temp.rejectNo = rejectNo;
                                        temp.rejectSku = rejectSku;
                                        temp.refundQuantity = refundQuantity;
                                        temp.itemQuantity = itemQuantity;
                                        temp.refundAmountSku = refundAmountSku;
                                        temp.dateCreated = new Date();
                                        temp.dateLastModified = new Date();
                                        temp.save(function (saveErr, saveResult) {
                                            if(saveErr) {
                                                logger.error("insert error code rejectSku..." + code + "@" + rejectSku);
                                                callbackInner(false);
                                            } else {
                                                logger.debug("insert success code rejectSku..." + code + "@" + rejectSku);
                                                callbackInner(false);
                                            }
                                        })
                                    }
                                });
                            }
                        });
                    }, function (tempError) {
                        logger.info("当前循环执行完成:" + tempError);
                        callback(null, length);
                    });
                } else {
                    logger.info("没有退款数据...");
                    callback(null, 0);
                }
            } else {
                logger.error(returnData);
                callback(null, 0);
            }
        } else {
            // 失败则重试
            callback(null, 0);
        }
    }).on('error', function (err) {
        // 失败则重试
        callback(null, 0);
    });

};

exports.refundStatusFor66OneDay = function(dayBeforeNstart, dayBeforeNend, callback) {
    var limitCount = 100;
    var allCount = 0;
    var regionOption = {'order_time': {$gte: dayBeforeNstart, $lt: dayBeforeNend}};
    var list = [];
    mtOrder.count(regionOption, function(err, tempCount) {
        if(tempCount > 0) {
            var endCount = parseInt((tempCount - 1) / limitCount) + 1;
            var countArray = [];
            for (var i = 0; i < tempCount; i = i + limitCount) {
                countArray.push(i);
            }
            logger.info(countArray);
            logger.info('预计分页执行次数:' + endCount);
            async.eachSeries(countArray, function (skipCount, callbackSkipCountInner) {
                logger.debug('for循环...' + skipCount);
                mtOrder.find(regionOption, {"order_id" : 1})
                    .limit(limitCount)
                    .skip(skipCount)
                    .sort({"_id": 1})
                    .exec(function (err2, orderData) {
                        logger.debug("exports.actuaryByStartEndDate 008");
                        logger.debug('Users.find...' + skipCount);
                        if (orderData && orderData.length > 0) {
                            async.eachSeries(orderData, function (tempOrder, callbackEachSeriesInner) {
                                list.push(tempOrder.order_id);
                                callbackEachSeriesInner(false);
                            }, function (tempErr) {
                                // 100条执行一次
                                logger.debug("100条执行一次...");
                                exports.refundStatusFor66(list, function (refundErr, refundResult) {
                                    if(refundResult && refundResult > 0) {
                                        allCount += refundResult;
                                        callbackSkipCountInner(false);
                                    } else {
                                        callbackSkipCountInner(false);
                                    }
                                });
                            });
                        } else {
                            callbackSkipCountInner(false);
                        }
                    });
            }, function (tempErr) {
                // 1天1天执行
                logger.debug("1天执行完成...");
                callback(null, allCount);
            });
        } else {
            callback(null, allCount);
        }
    });
};

exports.refundStatusFor66ByStartEndDate = function(fromDateSelect, toDateSelect, callback) {
    var fromToArray = toolUtil.getArrayDateByStartEndDateMin(fromDateSelect, toDateSelect);
    var allCount = 0;
    async.eachSeries(fromToArray, function (tempDate, callbackTempInner) {
        var dayBeforeNstart = new Date(moment(tempDate, "YYYY-MM-DD").format());
        var dayBeforeNend = new Date(moment(tempDate, "YYYY-MM-DD").add(1, "days").subtract(1, 'seconds').format("YYYY-MM-DD HH:mm:ss"));
        exports.refundStatusFor66OneDay(dayBeforeNstart, dayBeforeNend, function (tempErr, tempCount) {
            allCount += tempCount;
            callbackTempInner(false);
        });

    }, function (tempErr) {
        logger.debug("所有天执行完成...");
        callback(null, allCount);
    });
};
/*  宝宝树66小区五次改造-66订单退款状态    add   guo.xiaomin  20171120   end   */

// 查看某个期间是否有错误
exports.isCheckErrorByStartEndDate = function (startDate, endDate, callback) {
    var option = {"startDateTime": {$lte: startDate}, "endDateTime": {$gt: endDate}, "isError": true};
    mtOrderCheckLog.findOne(option, {"_id" : 1}, function (err, result) {
        if(result) {
            callback(null, true);
        } else {
            callback(null, false);
        }
    });
};

// 指定日期是否是小区大使
exports.namedDayIsModerator = function (userId, namedDay, callback) {
    var option = {"user": userId, "startDateTime": {$lte: namedDay}, "endDateTime": {$gt: namedDay}};
    RoleApply.findOne(option, {"status" : 1, "_id" : 0}, function (err, result) {
        if(result) {
            logger.debug("状态: " + result.status);
            callback(null, true);
        } else {
            callback(null, false);
        }
    });
};

// 查看邀请人是否是小区大使
exports.getInviterIsModerator = function (userId, callback) {
    userInvitation.findOne({"invitee": userId}, {"inviter": 1, "_id": 0}, function(err, tempInviter) {
        if(tempInviter) {
            callback(null, tempInviter.inviter);
            // // 有邀请人
            // User.findOne({
            //     "_id": currentInviter,
            //     "userRole": 4
            // }, {"_id": 1}, function (err, tempReturnDataUser) {
            //     if(tempReturnDataUser) {
            //         // 邀请人是小区大使
            //         callback(null, currentInviter);
            //     } else {
            //         // 邀请人不是小区大使
            //         callback(null, null);
            //     }
            // });
        } else {
            // 没有邀请人
            callback(err, null);
        }
    });
};

// 比较数据
exports.compareTwoData = function(oldData, newData) {
    if(oldData && newData) {
        return oldData == newData;
    } else if (!oldData && !newData) {
        return true;
    } else {
        return false;
    }
};

// 复核(数据存在)
exports.checkMtOrderByStartEndDate = function (orderList, version, autoFlag) {
    logger.info('checkMtOrderByStartEndDate start...');
    async.eachSeries(orderList, function (row, callbackInner) {
        logger.debug("exports.checkMtOrderByStartEndDate 001");
        var order_id = row.id; // 订单id
        var temp_order_time = row.createTime; // 下单时间(time类型)
        var order_time = moment(new Date(temp_order_time)).format("YYYY-MM-DD HH:mm:ss");

        var member_id = row.memberId; // 美囤id
        var order_uid = row.uid; // 下单人宝宝树id
        var order_uhp = row.uhp; // 下单人手机号
        // var order_user = row.order_user; // // 下单人唯一ID
        // var is_order_moderator = row.is_order_moderator; // 下单人是否是大使
        var share_uid = row.shareUid; // 分享人宝宝树id
        var share_uhp = row.shareUhp; // 分享人手机号
        // var share_user = row.share_user; // 分享人唯一ID
        // var is_share_moderator = row.is_share_moderator; // 分享人是否是大使
        var order_time_original = row.order_time; // 下单时间
        var price = row.price; // 单价(拼团活动价)
        var total = row.total; // 总价格
        var sku_code = row.skuCode; // 商品编码
        var sku_name = row.spuName; // 商品名称
        var quantity = row.quantity; // 数量
        var skuQuantity = row.skuQuantity; // sku购买数量
        var skuSubTotal = row.skuSubTotal; // sku优惠后总价

        <!--  宝宝树66小区六次改造 自营-非自营 mod   guo.xiaomin  20171222  start   -->
        // var itemSaleType = row.itemSaleType; // 销售类型 0-自营 1-非自营
        var originalItemSaleType = row.itemSaleType; // 销售类型 0-自营 1-非自营

        <!--  宝宝树66小区六次改造 自营-非自营 mod   guo.xiaomin  20171222  end   -->

        var wavesSign = row.wavesSign; //是否海淘商品,1-否，2-是，默认1

        <!--  宝宝树66小区五次改造 拼团新列追加 mod   guo.xiaomin  20171129  start   -->
        // var standard = row.standard; //是否标品 0 非标品  1标品  -1未设置
        var originalStandard = row.standard; // 原始值：是否标品 0 非标品  1标品  -1未设置
            // 商品分类：例：奶粉，纸尿裤
        var largeId = row.largeId; // 大分类
        var mediumId = row.mediumId; // 中分类
        var smallId = row.smallId; // 小分类
        <!--  宝宝树66小区五次改造 拼团新列追加 mod   guo.xiaomin  20171129  end   -->

        var orderType = row.orderType; //订单类型（1：普通  2：海淘 5：拼团）
        var isNewGroupOrder = row.isNewGroupOrder; //是否是新版本拼团订单 0-否;1-是
        var newGroupOrderStatus = row.newGroupOrderStatus; // 新版本拼团状态 0-已成团;1-未成团;2-待成团;3-已抢光
        var promotionId = row.promotionId; // 拼团活动id
        var proBizCode = row.proBizCode; // 拼团实例code
        var status = row.status; // 订单状态（已取消-0,待支付-2,拣货中-3,待发货-4,待收货-5,已收货-6,申请取消-8,取消中（等第三方确认）-9,退款完成-100）
        var doneTime = row.doneTime; // 完成时间(收货时间)
        var refundStatus = row.refundStatus; // 退款状态1-等待打款 2-退款中 3-退款成功 4-退款失败 5-取消退款 6-更换账号退款中 7-更换账号退款成功 8-等待提交
        var refundTime = row.refundTime; // 退款时间
        var modifyTime = row.modifyTime; // 订单状态变更时间

        var tempMtOrderCheckLog = new mtOrderCheckLog();
        tempMtOrderCheckLog.version = version; // 版本号
        tempMtOrderCheckLog.autoFlag = autoFlag; // 自动，手动
        tempMtOrderCheckLog.dateCreated = new Date(); // 创建日时
        tempMtOrderCheckLog.order_id = order_id;
        tempMtOrderCheckLog.order_time = order_time;

        // balanceStatus // 结算状态 1:已粗算，2:已精算，3:已结算，0:初始值（4种）
        var option = {'order_id': order_id, 'sku_code': sku_code, 'balanceStatus': {'$in' : [0, 1, 2]}};
        logger.debug("exports.checkMtOrderByStartEndDate 002");
        mtOrder.findOne(option, function(err, tempData) {
            logger.debug("exports.checkMtOrderByStartEndDate 003");
            // 如果不存在，则保存
            if (!tempData) {
                logger.debug("exports.checkMtOrderByStartEndDate 004");
                // save
                // 错误,订单不存在
                tempMtOrderCheckLog.isError = true;
                tempMtOrderCheckLog.comment = "表中无数据";
                // 美囤id
                tempMtOrderCheckLog.error_member_id = true;
                tempMtOrderCheckLog.new_member_id = member_id;
                // 下单人宝宝树id
                tempMtOrderCheckLog.error_order_uid = true;
                tempMtOrderCheckLog.new_order_uid = order_uid;
                // 下单人手机号
                tempMtOrderCheckLog.error_order_uhp = true;
                tempMtOrderCheckLog.new_order_uhp = order_uhp;
                // 分享人宝宝树id
                tempMtOrderCheckLog.error_share_uid = true;
                tempMtOrderCheckLog.new_share_uid = share_uid;
                // 分享人手机号
                tempMtOrderCheckLog.error_share_uhp = true;
                tempMtOrderCheckLog.new_share_uhp = share_uhp;
                // 单价(拼团活动价)
                tempMtOrderCheckLog.error_price = true;
                tempMtOrderCheckLog.new_price = price;
                // 总价格
                tempMtOrderCheckLog.error_total = true;
                tempMtOrderCheckLog.new_total = total;
                // 商品编码
                tempMtOrderCheckLog.error_sku_code = true;
                tempMtOrderCheckLog.new_sku_code = sku_code;
                // 商品名称
                tempMtOrderCheckLog.error_sku_name = true;
                tempMtOrderCheckLog.new_sku_name = sku_name;
                // 数量
                tempMtOrderCheckLog.error_quantity = true;
                tempMtOrderCheckLog.new_quantity = quantity;
                // sku购买数量
                tempMtOrderCheckLog.error_skuQuantity = true;
                tempMtOrderCheckLog.new_skuQuantity = skuQuantity;
                // sku优惠后总价
                tempMtOrderCheckLog.error_skuSubTotal = true;
                tempMtOrderCheckLog.new_skuSubTotal = quantity;
                // 销售类型 0-自营 1-非自营
                tempMtOrderCheckLog.error_itemSaleType = true;
                <!--  宝宝树66小区六次改造 自营非自营 mod   guo.xiaomin  20171212  start   -->
                // tempMtOrderCheckLog.new_itemSaleType = itemSaleType;
                tempMtOrderCheckLog.new_originalItemSaleType = originalItemSaleType;
                <!--  宝宝树66小区六次改造 自营非自营 mod   guo.xiaomin  20171212  end   -->
                // 是否海淘商品,1-否，2-是，默认1
                tempMtOrderCheckLog.error_wavesSign = true;
                tempMtOrderCheckLog.new_wavesSign = wavesSign;

                <!--  宝宝树66小区五次改造 拼团新列追加 mod   guo.xiaomin  20171129  start   -->
                // 是否标品 0 非标品  1标品  -1未设置
                tempMtOrderCheckLog.error_originalStandard = true;
                tempMtOrderCheckLog.new_originalStandard = originalStandard;

                // 大分类
                tempMtOrderCheckLog.error_largeId = true;
                tempMtOrderCheckLog.new_largeId = largeId;

                // 中分类
                tempMtOrderCheckLog.error_mediumId = true;
                tempMtOrderCheckLog.new_mediumId = mediumId;

                // 小分类
                tempMtOrderCheckLog.error_smallId = true;
                tempMtOrderCheckLog.new_smallId = smallId;
                <!--  宝宝树66小区五次改造 拼团新列追加 mod   guo.xiaomin  20171129  end   -->

                // 订单类型（1：普通  2：海淘 5：拼团）
                tempMtOrderCheckLog.error_orderType = true;
                tempMtOrderCheckLog.new_orderType = orderType;
                // 是否是新版本拼团订单 0-否;1-是
                tempMtOrderCheckLog.error_isNewGroupOrder = true;
                tempMtOrderCheckLog.new_isNewGroupOrder = isNewGroupOrder;
                // 新版本拼团状态 0-已成团;1-未成团;2-待成团;3-已抢光
                tempMtOrderCheckLog.error_newGroupOrderStatus = true;
                tempMtOrderCheckLog.new_newGroupOrderStatus = newGroupOrderStatus;
                // 拼团活动id
                tempMtOrderCheckLog.error_promotionId = true;
                tempMtOrderCheckLog.new_promotionId = promotionId;

                // 拼团实例code
                tempMtOrderCheckLog.error_proBizCode = true;
                tempMtOrderCheckLog.new_proBizCode = proBizCode;

                // 订单状态（已取消-0,新建-1,待支付-2,拣货中-3,待发货-4,待收货-5,已收货-6,申请取消-8,取消中（等第三方确认）-9,退款完成-100）
                tempMtOrderCheckLog.error_status = true;
                tempMtOrderCheckLog.new_status = status;

                // 完成时间(收货时间)
                tempMtOrderCheckLog.error_doneTime = true;
                tempMtOrderCheckLog.new_doneTime = doneTime;

                // 退款状态1-等待打款 2-退款中 3-退款成功 4-退款失败 5-取消退款 6-更换账号退款中 7-更换账号退款成功 8-等待提交
                tempMtOrderCheckLog.error_refundStatus = true;
                tempMtOrderCheckLog.new_refundStatus = refundStatus;

                // 退款时间
                tempMtOrderCheckLog.error_refundTime = true;
                tempMtOrderCheckLog.new_refundTime = refundTime;

                tempMtOrderCheckLog.save(function (tmpErr, tmpResult) {
                    logger.debug("exports.checkMtOrderByStartEndDate 005");
                    callbackInner(false);
                });
            } else {
                logger.debug("exports.checkMtOrderByStartEndDate 006");
                console.log(row);
                console.log(option);
                console.log(order_id);
                // 正常对比数据
                // 那些列需要比较
                var temp_order_id = tempData.order_id; // 订单id
                var temp_data_order_time = tempData.order_time ? tempData.order_time.getTime() : tempData.order_time; // 下单时间(time类型)
                var temp_member_id = tempData.member_id; // 美囤id
                var temp_order_uid = tempData.order_uid; // 下单人宝宝树id
                var temp_order_uhp = tempData.order_uhp; // 下单人手机号
                var temp_order_user = tempData.order_user; // // 下单人唯一ID
                // var temp_is_order_moderator = tempData.is_order_moderator; // 下单人是否是大使
                var temp_share_uid = tempData.share_uid; // 分享人宝宝树id
                var temp_share_uhp = tempData.share_uhp; // 分享人手机号
                var temp_share_user = tempData.share_user; // 分享人唯一ID
                // var temp_is_share_moderator = tempData.is_share_moderator; // 分享人是否是大使
                var temp_price = tempData.price; // 单价(拼团活动价)
                var temp_total = tempData.total; // 总价格
                var temp_sku_code = tempData.sku_code; // 商品编码
                var temp_sku_name = tempData.sku_name; // 商品名称
                var temp_quantity = tempData.quantity; // 数量
                var temp_skuQuantity = tempData.skuQuantity; // sku购买数量
                var temp_skuSubTotal = tempData.skuSubTotal; // sku优惠后总价

                <!--  宝宝树66小区六次改造 自营非自营 mod   guo.xiaomin  20171212  start   -->
                var temp_itemSaleType = tempData.originalItemSaleType; // 销售类型 0-自营 1-非自营
                <!--  宝宝树66小区六次改造 自营非自营 mod   guo.xiaomin  20171212  end   -->

                var temp_wavesSign = tempData.wavesSign; //是否海淘商品,1-否，2-是，默认1

                <!--  宝宝树66小区五次改造 拼团新列追加 mod   guo.xiaomin  20171129  start   -->
                var temp_standard = tempData.originalStandard; //是否标品 0 非标品  1标品  -1未设置

                var temp_largeId = tempData.largeId; // 大分类
                var temp_mediumId = tempData.mediumId; // 中分类
                var temp_smallId = tempData.smallId; // 小分类
                <!--  宝宝树66小区五次改造 拼团新列追加 mod   guo.xiaomin  20171129  end   -->

                var temp_orderType = tempData.orderType; //订单类型（1：普通  2：海淘 5：拼团）
                var temp_isNewGroupOrder = tempData.isNewGroupOrder; //是否是新版本拼团订单 0-否;1-是
                var temp_newGroupOrderStatus = tempData.newGroupOrderStatus; // 新版本拼团状态 0-已成团;1-未成团;2-待成团;3-已抢光
                var temp_promotionId = tempData.promotionId; // 拼团活动id
                var temp_proBizCode = tempData.proBizCode; // 拼团实例code
                var temp_status = tempData.status; // 订单状态（已取消-0,待支付-2,拣货中-3,待发货-4,待收货-5,已收货-6,申请取消-8,取消中（等第三方确认）-9,退款完成-100）
                var temp_doneTime = tempData.doneTime ? tempData.doneTime.getTime() : tempData.doneTime; // 完成时间(收货时间)
                var temp_refundStatus = tempData.refundStatus; // 退款状态1-等待打款 2-退款中 3-退款成功 4-退款失败 5-取消退款 6-更换账号退款中 7-更换账号退款成功 8-等待提交
                var temp_refundTime = tempData.refundTime ? tempData.refundTime.getTime() : tempData.refundTime; // 退款时间
                var temp_modifyTime = tempData.modifyTime ? tempData.modifyTime.getTime() : tempData.modifyTime; // 订单状态变更时间

                console.log();

                // 是否出错 true:出错;false:未出错
                var isError = false;

                // 美囤id
                if (!exports.compareTwoData(temp_member_id, member_id)) {
                    tempMtOrderCheckLog.error_member_id = true;
                    tempMtOrderCheckLog.old_member_id = temp_member_id;
                    tempMtOrderCheckLog.new_member_id = member_id;
                    isError = true;
                }

                // 下单人宝宝树id
                if (!exports.compareTwoData(temp_order_uid, order_uid)) {
                    tempMtOrderCheckLog.error_order_uid = true;
                    tempMtOrderCheckLog.old_order_uid = temp_order_uid;
                    tempMtOrderCheckLog.new_order_uid = order_uid;
                    isError = true;
                }

                // 下单人手机号
                if (!exports.compareTwoData(temp_order_uhp, order_uhp)) {
                    tempMtOrderCheckLog.error_order_uhp = true;
                    tempMtOrderCheckLog.old_order_uhp = temp_order_uhp;
                    tempMtOrderCheckLog.new_order_uhp = order_uhp;
                    isError = true;
                }

                // 分享人宝宝树id
                if (!exports.compareTwoData(temp_share_uid, share_uid)) {
                    tempMtOrderCheckLog.error_share_uid = true;
                    tempMtOrderCheckLog.old_share_uid = temp_share_uid;
                    tempMtOrderCheckLog.new_share_uid = share_uid;
                    isError = true;
                }

                // 分享人手机号
                if (!exports.compareTwoData(temp_share_uhp, share_uhp)) {
                    tempMtOrderCheckLog.error_share_uhp = true;
                    tempMtOrderCheckLog.old_share_uhp = temp_share_uhp;
                    tempMtOrderCheckLog.new_share_uhp = share_uhp;
                    isError = true;
                }

                // 单价(拼团活动价)
                if (!exports.compareTwoData(temp_price, price)) {
                    tempMtOrderCheckLog.error_price = true;
                    tempMtOrderCheckLog.old_price = temp_price;
                    tempMtOrderCheckLog.new_price = price;
                    isError = true;
                }

                // 总价格
                if (!exports.compareTwoData(temp_total, total)) {
                    tempMtOrderCheckLog.error_total = true;
                    tempMtOrderCheckLog.old_total = temp_total;
                    tempMtOrderCheckLog.new_total = total;
                    isError = true;
                }

                // 商品编码
                if (!exports.compareTwoData(temp_sku_code, sku_code)) {
                    tempMtOrderCheckLog.error_sku_code = true;
                    tempMtOrderCheckLog.old_sku_code = temp_sku_code;
                    tempMtOrderCheckLog.new_sku_code = sku_code;
                    isError = true;
                }

                // 商品名称
                if (!exports.compareTwoData(temp_sku_name, sku_name)) {
                    tempMtOrderCheckLog.error_sku_name = true;
                    tempMtOrderCheckLog.old_sku_name = temp_sku_name;
                    tempMtOrderCheckLog.new_sku_name = sku_name;
                    isError = true;
                }

                // 数量
                if (!exports.compareTwoData(temp_quantity, quantity)) {
                    tempMtOrderCheckLog.error_quantity = true;
                    tempMtOrderCheckLog.old_quantity = temp_quantity;
                    tempMtOrderCheckLog.new_quantity = quantity;
                    isError = true;
                }

                // sku购买数量
                if (!exports.compareTwoData(temp_skuQuantity, skuQuantity)) {
                    tempMtOrderCheckLog.error_skuQuantity = true;
                    tempMtOrderCheckLog.old_skuQuantity = temp_skuQuantity;
                    tempMtOrderCheckLog.new_skuQuantity = skuQuantity;
                    isError = true;
                }

                // sku优惠后总价
                if (!exports.compareTwoData(temp_skuSubTotal, skuSubTotal)) {
                    tempMtOrderCheckLog.error_skuSubTotal = true;
                    tempMtOrderCheckLog.old_skuSubTotal = temp_skuSubTotal;
                    tempMtOrderCheckLog.new_skuSubTotal = skuSubTotal;
                    isError = true;
                }

                // 销售类型 0-自营 1-非自营
                if (!exports.compareTwoData(temp_itemSaleType, originalItemSaleType)) {
                    tempMtOrderCheckLog.error_originalItemSaleType = true;
                    tempMtOrderCheckLog.old_originalItemSaleType = temp_itemSaleType;
                    tempMtOrderCheckLog.new_originalItemSaleType = originalItemSaleType;
                    isError = true;
                }

                // 是否海淘商品,1-否，2-是，默认1
                if (!exports.compareTwoData(temp_wavesSign, wavesSign)) {
                    tempMtOrderCheckLog.error_wavesSign = true;
                    tempMtOrderCheckLog.old_wavesSign = temp_wavesSign;
                    tempMtOrderCheckLog.new_wavesSign = wavesSign;
                    isError = true;
                }

                // 是否标品 0 非标品  1标品  -1未设置
                if (!exports.compareTwoData(temp_standard, originalStandard)) {
                    tempMtOrderCheckLog.error_standard = true;
                    tempMtOrderCheckLog.old_standard = temp_standard;
                    tempMtOrderCheckLog.new_standard = originalStandard;
                    isError = true;
                }


                <!--  宝宝树66小区五次改造 拼团新列追加 mod   guo.xiaomin  20171129  start   -->

                // 大分类
                if (!exports.compareTwoData(temp_largeId, largeId)) {
                    tempMtOrderCheckLog.error_largeId = true;
                    tempMtOrderCheckLog.old_largeId = temp_largeId;
                    tempMtOrderCheckLog.new_largeId = largeId;
                    isError = true;
                }

                // 中分类
                if (!exports.compareTwoData(temp_mediumId, mediumId)) {
                    tempMtOrderCheckLog.error_mediumId = true;
                    tempMtOrderCheckLog.old_mediumId = temp_mediumId;
                    tempMtOrderCheckLog.new_mediumId = mediumId;
                    isError = true;
                }

                // 小分类
                if (!exports.compareTwoData(temp_smallId, smallId)) {
                    tempMtOrderCheckLog.error_smallId = true;
                    tempMtOrderCheckLog.old_smallId = temp_smallId;
                    tempMtOrderCheckLog.new_smallId = smallId;
                    isError = true;
                }
                <!--  宝宝树66小区五次改造 拼团新列追加 mod   guo.xiaomin  20171129  end   -->

                // 订单类型（1：普通  2：海淘 5：拼团）
                if (!exports.compareTwoData(temp_orderType, orderType)) {
                    tempMtOrderCheckLog.error_orderType = true;
                    tempMtOrderCheckLog.old_orderType = temp_orderType;
                    tempMtOrderCheckLog.new_orderType = orderType;
                    isError = true;
                }

                // 是否是新版本拼团订单 0-否;1-是
                if (!exports.compareTwoData(temp_isNewGroupOrder, isNewGroupOrder)) {
                    tempMtOrderCheckLog.error_isNewGroupOrder = true;
                    tempMtOrderCheckLog.old_isNewGroupOrder = temp_isNewGroupOrder;
                    tempMtOrderCheckLog.new_isNewGroupOrder = isNewGroupOrder;
                    isError = true;
                }

                // 新版本拼团状态 0-已成团;1-未成团;2-待成团;3-已抢光
                if (!exports.compareTwoData(temp_newGroupOrderStatus, newGroupOrderStatus)) {
                    tempMtOrderCheckLog.error_newGroupOrderStatus = true;
                    tempMtOrderCheckLog.old_newGroupOrderStatus = temp_newGroupOrderStatus;
                    tempMtOrderCheckLog.new_newGroupOrderStatus = newGroupOrderStatus;
                    isError = true;
                }

                // 拼团活动id
                if (!exports.compareTwoData(temp_promotionId, promotionId)) {
                    tempMtOrderCheckLog.error_promotionId = true;
                    tempMtOrderCheckLog.old_promotionId = temp_promotionId;
                    tempMtOrderCheckLog.new_promotionId = promotionId;
                    isError = true;
                }

                // 拼团实例code
                if (!exports.compareTwoData(temp_proBizCode, proBizCode)) {
                    tempMtOrderCheckLog.error_proBizCode = true;
                    tempMtOrderCheckLog.old_proBizCode = temp_proBizCode;
                    tempMtOrderCheckLog.new_proBizCode = proBizCode;
                    isError = true;
                }

                // 完成时间(收货时间)
                if (!exports.compareTwoData(temp_doneTime, doneTime)) {
                    tempMtOrderCheckLog.error_doneTime = true;
                    tempMtOrderCheckLog.old_doneTime = temp_doneTime;
                    tempMtOrderCheckLog.new_doneTime = doneTime;
                    isError = true;
                }

                // 退款状态1-等待打款 2-退款中 3-退款成功 4-退款失败 5-取消退款 6-更换账号退款中 7-更换账号退款成功 8-等待提交
                if (!exports.compareTwoData(temp_refundStatus, refundStatus)) {
                    tempMtOrderCheckLog.error_refundStatus = true;
                    tempMtOrderCheckLog.old_refundStatus = temp_refundStatus;
                    tempMtOrderCheckLog.new_refundStatus = refundStatus;
                    isError = true;
                }

                // 退款时间
                if (!exports.compareTwoData(temp_refundTime, refundTime)) {
                    tempMtOrderCheckLog.error_refundTime = true;
                    tempMtOrderCheckLog.old_refundTime = temp_refundTime;
                    tempMtOrderCheckLog.new_refundTime = refundTime;
                    isError = true;
                }

                // 订单状态变更时间
                if (!exports.compareTwoData(temp_modifyTime, modifyTime)) {
                    tempMtOrderCheckLog.error_modifyTime = true;
                    tempMtOrderCheckLog.old_modifyTime = temp_modifyTime;
                    tempMtOrderCheckLog.new_modifyTime = modifyTime;
                    isError = true;
                }

                var isOnlyStatusError = false;
                // 订单状态（已取消-0,新建-1,待支付-2,拣货中-3,待发货-4,待收货-5,已收货-6,申请取消-8,取消中（等第三方确认）-9,退款完成-100）
                if (!exports.compareTwoData(temp_status, status)) {
                    tempMtOrderCheckLog.error_status = true;
                    tempMtOrderCheckLog.old_status = temp_status;
                    tempMtOrderCheckLog.new_status = status;
                    if(!isError) {
                        isOnlyStatusError = true;
                    }
                    isError = true;
                }

                tempMtOrderCheckLog.isError = isError;
                if (isError) {
                    tempMtOrderCheckLog.comment = "部分错误";
                    // if(isOnlyStatusError) {
                    //     tempMtOrderCheckLog.comment = "没有错误";
                    // }
                } else {
                    tempMtOrderCheckLog.comment = "没有错误";
                }

                // var updateOption = {'order_id': order_id, 'sku_code': sku_code};
                // var tempMtOrder = {'status': status};
                // mtOrder.update(updateOption, tempMtOrder).exec(function (err, updateResult) {
                //     // save
                //     tempMtOrderCheckLog.save(function (tmpErr, tmpResult) {
                //         logger.debug("exports.checkMtOrderByStartEndDate 007");
                //         callbackInner(false);
                //     });
                // });

                // save
                tempMtOrderCheckLog.save(function (tmpErr, tmpResult) {
                    logger.debug("exports.checkMtOrderByStartEndDate 007");
                    callbackInner(false);
                });
            }
        });
    }, function (err) {
        logger.info('checkMtOrderByStartEndDate end...');
        return true;
    });
};

// 粗算，精算
// flag = 已粗算，已精算，已结算，0:初始值（4种）
exports.actuaryByStartEndDate = function (startMoment, endMoment, flag, version, autoFlag, callback) {
    logger.debug("exports.actuaryByStartEndDate 001");
    // flag=1,粗算开始;flag=2,精算开始
    var eachSeriesInnerCount = 0;
    var limitCount = 100;
    // balanceStatus : Number, // 结算状态 1:已粗算，2:已精算，3:已结算，0:初始值（4种）
    // 已收货-6
    var regionOption = {'order_time': {$gte: startMoment, $lte: endMoment}};
    // if(flag == 2) {
        regionOption.balanceStatus = {'$in' : [0, 1, 2]};
        // regionOption.status = 6;
    // } else if(flag == 1) {
    //     regionOption.balanceStatus = {$in: [0, 1]};
    // }
    logger.debug(regionOption);
    logger.debug("exports.actuaryByStartEndDate 002");
    mtOrder.count(regionOption, function(err, tempCount) {
        logger.debug("exports.actuaryByStartEndDate 003");
        if(flag == 2) {
            logger.debug("精算的mtOrder.count is..." + tempCount);
            // regionOption.status = 6;
        } else if(flag == 1) {
            logger.debug("粗算的mtOrder.count is..." + tempCount);
        }
        if (err) {
            logger.error(err);
        }
        if (tempCount == 0) {
            logger.debug("exports.actuaryByStartEndDate 004");
            callback(null, 0);
        } else {
            logger.debug("exports.actuaryByStartEndDate 005");
            logger.debug("选择区间的订单件数为..." + tempCount);
            var endCount = parseInt((tempCount - 1) / limitCount) + 1;
            var countArray = [];
            for (var i = 0; i < tempCount; i = i + limitCount) {
                countArray.push(i);
            }
            logger.info(countArray);
            logger.info('预计分页执行次数:' + endCount);
            logger.debug("exports.actuaryByStartEndDate 006");
            async.eachSeries(countArray, function (skipCount, callbackSkipCountInner) {
                logger.debug("exports.actuaryByStartEndDate 007");
                logger.debug('for循环...' + skipCount);
                mtOrder.find(regionOption)
                    .limit(limitCount)
                    .skip(skipCount)
                    .sort({"_id": 1})
                    .exec(function (err2, orderData) {
                        logger.debug("exports.actuaryByStartEndDate 008");
                        logger.debug('Users.find...' + skipCount);
                        if (orderData != null) {
                            logger.debug("exports.actuaryByStartEndDate 009");
                            async.eachSeries(orderData, function (tempOrder, callbackEachSeriesInner) {
                                logger.debug("exports.actuaryByStartEndDate 010");
                                // logger.debug('async.eachSeriesN个执行完成...' + ++eachSeriesInnerCount);
                                // 原则：1个订单只能算1份业绩
                                // 总价格
                                // var total = tempOrder.total; // 旧
                                // 1条数据(订单号+商品码)一个佣金
                                var skuSubTotal = tempOrder.total; // 新
                                if(!skuSubTotal) {
                                    skuSubTotal = tempOrder.total; // TODO 临时兼容,美囤20171121上线后去掉此部分
                                }
                                // 佣金比例
                                // var commissionPercent = toolUtil.getCommissionPercent(tempOrder);
                                // 佣金比例
                                var commissionPercent = 0;
                                // 佣金类型名称
                                var commissionName = null;
                                // 佣金比例+佣金类型名称
                                var commissionPercentName = toolUtil.getCommissionPercentName(tempOrder);
                                if (commissionPercentName) {
                                    commissionPercent = commissionPercentName.commissionPercent;
                                    commissionName = commissionPercentName.commissionName;
                                }
                                // 当前订单佣金
                                // var commissionPrice = commissionPercent * total; // 旧
                                var commissionPrice = commissionPercent * skuSubTotal; // 新
                                // 保留4位小数
                                commissionPrice = commissionPrice.toFixed(2);
                                var saveOrder = {};
                                saveOrder.prepareCommissionPrice = commissionPrice;
                                var order_time = tempOrder.order_time; // 下单日期
                                // 佣金比例
                                saveOrder.commissionPercent = commissionPercent;
                                // 佣金类型名称
                                saveOrder.commissionName = commissionName;
                                // 邀请提成比例
                                saveOrder.commissionDrawPercentage = commissionDrawPercentage;
                                // 上次精算日期
                                saveOrder.lastActuaryDate = new Date();
                                // 结算状态
                                saveOrder.balanceStatus = flag;
                                // 分享人是否是大使
                                var share_user = tempOrder.share_user;
                                var sku_code = tempOrder.sku_code;
                                var option = {};
                                var order_id = tempOrder.order_id;
                                option.order_id = order_id;
                                option.sku_code = sku_code;
                                // 数据唯一键为:订单ID(order_id) + 商品码(sku_code)

                                var tempMtOrderActuaryLog = new mtOrderActuaryLog();
                                tempMtOrderActuaryLog.version = version;
                                tempMtOrderActuaryLog.autoFlag = autoFlag;
                                // tempMtOrderActuaryLog.commissionDrawPercentage = commissionDrawPercentage;
                                tempMtOrderActuaryLog.order_id = order_id;
                                tempMtOrderActuaryLog.order_time = order_time;
                                if (flag == 1) {
                                    tempMtOrderActuaryLog.actuaryFlag = "粗算";
                                } else if (flag == 2) {
                                    tempMtOrderActuaryLog.actuaryFlag = "精算";
                                }
                                // 2~6，计算8个值
                                var tempStatus = tempOrder.status;
                                logger.debug("订单以及状态..." + order_id + "@" + tempStatus);
                                logger.debug("exports.actuaryByStartEndDate 011..." + order_id);
                                // 拣货中-3,待发货-4,待收货-5,已收货-6
                                // if(tempStatus >= 3 && tempStatus <= 6)
                                // {
                                    logger.debug("exports.actuaryByStartEndDate 012..." + order_id);
                                    // var isMtOrderActuaryLogError = false;
                                    exports.namedDayIsModerator(share_user, order_time, function (namedErr, isShareModerator) {
                                        logger.debug("exports.actuaryByStartEndDate 013..." + order_id);
                                        if (isShareModerator) {
                                            logger.debug("exports.actuaryByStartEndDate 014..." + order_id);
                                            // 分享订单佣金
                                            var shareCommissionTemp = toolUtil.get4CommissionPrice(commissionPrice, tempStatus);
                                            saveOrder.shareCommission = Number(shareCommissionTemp).toFixed(2);
                                            saveOrder.realCommissionPrice1 = saveOrder.shareCommission;
                                            // 分享订单佣金归属
                                            saveOrder.shareCommissionUser = toolUtil.get4CommissionUser(share_user, tempStatus);
                                            saveOrder.selfPurchase = 0; // 自购订单佣金
                                            saveOrder.selfPurchaseUser = null; // 自购订单佣金归属
                                            saveOrder.communityCommission = 0; // 小区订单佣金
                                            saveOrder.communityCommissionUser = null; // 小区订单佣金归属
                                            saveOrder.inviterCommission = 0; // 邀请人佣金
                                            saveOrder.inviterCommissionUser = null; // 邀请人佣金归属
                                            saveOrder.comment = "分享订单佣金！";
                                            saveOrder.orderCommissionType = 1;
                                            logger.debug("分享订单佣金！");
                                            exports.getInviterIsModerator(share_user, function (shareErr, shareReturnData) {
                                                logger.debug("exports.actuaryByStartEndDate 015..." + order_id);
                                                if (shareReturnData) {
                                                    logger.debug("exports.actuaryByStartEndDate 016..." + order_id);
                                                    exports.namedDayIsModerator(shareReturnData, order_time, function (namedErr, isModerator) {
                                                        logger.debug("exports.actuaryByStartEndDate 017..." + order_id);
                                                        if (isModerator) {
                                                            var inviterCommissionTemp = toolUtil.get4CommissionPrice(commissionPrice, tempStatus) * commissionDrawPercentage;
                                                            saveOrder.inviterCommission = Number(inviterCommissionTemp).toFixed(2);
                                                            saveOrder.realCommissionPrice2 = saveOrder.inviterCommission;
                                                            saveOrder.inviterCommissionUser = toolUtil.get4CommissionUser(shareReturnData, tempStatus);
                                                            saveOrder.isInviterCommissionStatus = true;
                                                        }
                                                        mtOrder.update(option, saveOrder).exec(function (err, updateResult) {
                                                            logger.debug("exports.actuaryByStartEndDate 018..." + order_id);
                                                            if (err) {
                                                                logger.debug("exports.actuaryByStartEndDate 019..." + order_id);
                                                                // 错误
                                                                tempMtOrderActuaryLog.isError = true;
                                                                tempMtOrderActuaryLog.comment = "分享人是大使订单佣金保存错误";
                                                                tempMtOrderActuaryLog.save(function (saveErr, saveResult) {
                                                                    callbackEachSeriesInner(false);
                                                                });
                                                            } else {
                                                                logger.debug("exports.actuaryByStartEndDate 020..." + order_id);
                                                                // 保存数据
                                                                logger.info(updateResult);
                                                                tempMtOrderActuaryLog.isError = false;
                                                                tempMtOrderActuaryLog.comment = "分享是大使订单佣金保存正确";
                                                                tempMtOrderActuaryLog.save(function (saveErr, saveResult) {
                                                                    callbackEachSeriesInner(false);
                                                                });
                                                            }
                                                        });
                                                    });
                                                } else {
                                                    logger.debug("exports.actuaryByStartEndDate 021..." + order_id);
                                                    mtOrder.update(option, saveOrder).exec(function (err, updateResult) {
                                                        logger.debug("exports.actuaryByStartEndDate 022..." + order_id);
                                                        if (err) {
                                                            logger.debug("exports.actuaryByStartEndDate 023..." + order_id);
                                                            // 错误
                                                            tempMtOrderActuaryLog.isError = true;
                                                            tempMtOrderActuaryLog.comment = "分享人不是大使订单佣金保存错误";
                                                            tempMtOrderActuaryLog.save(function (saveErr, saveResult) {
                                                                callbackEachSeriesInner(false);
                                                            });
                                                        } else {
                                                            logger.debug("exports.actuaryByStartEndDate 024..." + order_id);
                                                            // 保存数据
                                                            logger.info(updateResult);
                                                            tempMtOrderActuaryLog.isError = false;
                                                            tempMtOrderActuaryLog.comment = "分享人不是大使订单佣金保存正确";
                                                            tempMtOrderActuaryLog.save(function (saveErr, saveResult) {
                                                                callbackEachSeriesInner(false);
                                                            });
                                                        }
                                                    });
                                                }
                                            });
                                        } else {
                                            logger.debug("exports.actuaryByStartEndDate 025..." + order_id);
                                            // 下单人
                                            var order_user = tempOrder.order_user;
                                            exports.namedDayIsModerator(order_user, order_time, function (namedErr, isOrderModerator) {
                                                logger.debug("exports.actuaryByStartEndDate 026..." + order_id);
                                                // 下单人是否是大使
                                                if (isOrderModerator) {
                                                    logger.debug("exports.actuaryByStartEndDate 027..." + order_id);
                                                    saveOrder.shareCommission = 0; // 分享订单佣金
                                                    saveOrder.shareCommissionUser = null; // 分享订单佣金归属
                                                    saveOrder.communityCommission = 0; // 小区订单佣金
                                                    saveOrder.communityCommissionUser = null; // 小区订单佣金归属
                                                    saveOrder.inviterCommission = 0; // 邀请人佣金
                                                    saveOrder.inviterCommissionUser = null; // 邀请人佣金归属
                                                    // 自购订单佣金
                                                    var selfPurchaseTemp = toolUtil.get4CommissionPrice(commissionPrice, tempStatus);
                                                    saveOrder.selfPurchase = Number(selfPurchaseTemp).toFixed(2);
                                                    saveOrder.realCommissionPrice1 = saveOrder.selfPurchase;
                                                    // 自购订单佣金归属
                                                    saveOrder.selfPurchaseUser = toolUtil.get4CommissionUser(order_user, tempStatus);
                                                    saveOrder.comment = "自购订单佣金！";
                                                    logger.debug("自购订单佣金！");
                                                    saveOrder.orderCommissionType = 2;
                                                    exports.getInviterIsModerator(order_user, function (orderErr, orderReturnData) {
                                                        logger.debug("exports.actuaryByStartEndDate 028..." + order_id);
                                                        if (orderReturnData) {
                                                            logger.debug("exports.actuaryByStartEndDate 029..." + order_id);
                                                            exports.namedDayIsModerator(orderReturnData, order_time, function (namedErr, isModerator) {
                                                                logger.debug("exports.actuaryByStartEndDate 030..." + order_id);
                                                                if (isModerator) {
                                                                    var inviterCommissionTemp = toolUtil.get4CommissionPrice(commissionPrice, tempStatus) * commissionDrawPercentage;
                                                                    saveOrder.inviterCommission = Number(inviterCommissionTemp).toFixed(2);
                                                                    saveOrder.realCommissionPrice2 = saveOrder.inviterCommission;
                                                                    saveOrder.inviterCommissionUser = toolUtil.get4CommissionUser(orderReturnData, tempStatus);
                                                                    saveOrder.isInviterCommissionStatus = true;
                                                                }
                                                                mtOrder.update(option, saveOrder).exec(function (err, updateResult) {
                                                                    logger.debug("exports.actuaryByStartEndDate 031..." + order_id);
                                                                    if (err) {
                                                                        logger.debug("exports.actuaryByStartEndDate 032..." + order_id);
                                                                        // 错误
                                                                        tempMtOrderActuaryLog.isError = true;
                                                                        tempMtOrderActuaryLog.comment = "自购人是大使订单佣金保存错误";
                                                                        tempMtOrderActuaryLog.save(function (saveErr, saveResult) {
                                                                            callbackEachSeriesInner(false);
                                                                        });
                                                                    } else {
                                                                        logger.debug("exports.actuaryByStartEndDate 033..." + order_id);
                                                                        // 保存数据
                                                                        logger.info(updateResult);
                                                                        tempMtOrderActuaryLog.isError = false;
                                                                        tempMtOrderActuaryLog.comment = "自购是大使订单佣金保存正确";
                                                                        tempMtOrderActuaryLog.save(function (saveErr, saveResult) {
                                                                            callbackEachSeriesInner(false);
                                                                        });
                                                                    }
                                                                });
                                                            });
                                                        } else {
                                                            logger.debug("exports.actuaryByStartEndDate 034..." + order_id);
                                                            mtOrder.update(option, saveOrder).exec(function (err, updateResult) {
                                                                logger.debug("exports.actuaryByStartEndDate 035..." + order_id);
                                                                if (err) {
                                                                    logger.debug("exports.actuaryByStartEndDate 036..." + order_id);
                                                                    // 错误
                                                                    tempMtOrderActuaryLog.isError = true;
                                                                    tempMtOrderActuaryLog.comment = "自购人不是大使订单佣金保存错误";
                                                                    tempMtOrderActuaryLog.save(function (saveErr, saveResult) {
                                                                        callbackEachSeriesInner(false);
                                                                    });
                                                                } else {
                                                                    logger.debug("exports.actuaryByStartEndDate 037..." + order_id);
                                                                    // 保存数据
                                                                    logger.info(updateResult);
                                                                    tempMtOrderActuaryLog.isError = false;
                                                                    tempMtOrderActuaryLog.comment = "自购人不是大使订单佣金保存正确";
                                                                    tempMtOrderActuaryLog.save(function (saveErr, saveResult) {
                                                                        callbackEachSeriesInner(false);
                                                                    });
                                                                }
                                                            });
                                                        }
                                                    });
                                                } else {
                                                    logger.debug("exports.actuaryByStartEndDate 038..." + order_id);
                                                    // 下单人所在小区
                                                    // 下单人所在小区的小区大使
                                                    User.findOne({
                                                        "_id": order_user
                                                    }, {"community": 1}, function (err, tempReturnData) {
                                                        logger.debug("exports.actuaryByStartEndDate 039..." + order_id);
                                                        if (tempReturnData) {
                                                            logger.debug("exports.actuaryByStartEndDate 040..." + order_id);
                                                            RoleApply.findOne({
                                                                "community": tempReturnData.community,
                                                                "startDateTime": {$lte: order_time},
                                                                "endDateTime": {$gt: order_time}
                                                            }, {"user": 1}, function (err, tempReturnDataUser) {
                                                                logger.debug("exports.actuaryByStartEndDate 041..." + order_id);
                                                                // 当前小区大使ID
                                                                if (tempReturnDataUser) {
                                                                    logger.debug("exports.actuaryByStartEndDate 042..." + order_id);
                                                                    // 当前小区有大使
                                                                    saveOrder.shareCommission = 0; // 分享订单佣金
                                                                    saveOrder.shareCommissionUser = null; // 分享订单佣金归属
                                                                    saveOrder.selfPurchase = 0; // 自购订单佣金
                                                                    saveOrder.selfPurchaseUser = null; // 自购订单佣金归属
                                                                    saveOrder.inviterCommission = 0; // 邀请人佣金
                                                                    saveOrder.inviterCommissionUser = null; // 邀请人佣金归属
                                                                    // 小区订单佣金
                                                                    var communityCommissionTemp = toolUtil.get4CommissionPrice(commissionPrice, tempStatus) * commissionDrawPercentage;
                                                                    saveOrder.communityCommission = Number(communityCommissionTemp).toFixed(2);
                                                                    saveOrder.realCommissionPrice1 = saveOrder.communityCommission;
                                                                    var tempUserId = tempReturnDataUser.user;
                                                                    // 小区订单佣金归属
                                                                    saveOrder.communityCommissionUser = toolUtil.get4CommissionUser(tempUserId, tempStatus);
                                                                    saveOrder.comment = "小区订单佣金！";
                                                                    saveOrder.orderCommissionType = 3;
                                                                    logger.debug("小区订单佣金！");
                                                                    exports.getInviterIsModerator(tempUserId, function (communityErr, communityReturnData) {
                                                                        logger.debug("exports.actuaryByStartEndDate 043..." + order_id);
                                                                        if (communityReturnData) {
                                                                            logger.debug("exports.actuaryByStartEndDate 044..." + order_id);
                                                                            exports.namedDayIsModerator(communityReturnData, order_time, function (namedErr, isModerator) {
                                                                                logger.debug("exports.actuaryByStartEndDate 045..." + order_id);
                                                                                if (isModerator) {
                                                                                    var inviterCommissionTemp = toolUtil.get4CommissionPrice(commissionPrice, tempStatus) * commissionDrawPercentage;
                                                                                    saveOrder.inviterCommission = Number(inviterCommissionTemp).toFixed(2);
                                                                                    saveOrder.realCommissionPrice2 = saveOrder.inviterCommission;
                                                                                    saveOrder.inviterCommissionUser = toolUtil.get4CommissionUser(communityReturnData, tempStatus);
                                                                                    saveOrder.isInviterCommissionStatus = true;
                                                                                }
                                                                                mtOrder.update(option, saveOrder).exec(function (err, updateResult) {
                                                                                    logger.debug("exports.actuaryByStartEndDate 046..." + order_id);
                                                                                    if (err) {
                                                                                        logger.debug("exports.actuaryByStartEndDate 047..." + order_id);
                                                                                        // 错误
                                                                                        tempMtOrderActuaryLog.isError = true;
                                                                                        tempMtOrderActuaryLog.comment = "小区邀请人是大使订单佣金保存错误";
                                                                                        tempMtOrderActuaryLog.save(function (saveErr, saveResult) {
                                                                                            callbackEachSeriesInner(false);
                                                                                        });
                                                                                    } else {
                                                                                        logger.debug("exports.actuaryByStartEndDate 048..." + order_id);
                                                                                        // 保存数据
                                                                                        logger.info(updateResult);
                                                                                        tempMtOrderActuaryLog.isError = false;
                                                                                        tempMtOrderActuaryLog.comment = "小区邀请人是大使订单佣金保存正确";
                                                                                        tempMtOrderActuaryLog.save(function (saveErr, saveResult) {
                                                                                            callbackEachSeriesInner(false);
                                                                                        });
                                                                                    }
                                                                                });
                                                                            });
                                                                        } else {
                                                                            logger.debug("exports.actuaryByStartEndDate 049..." + order_id);
                                                                            mtOrder.update(option, saveOrder).exec(function (err, updateResult) {
                                                                                logger.debug("exports.actuaryByStartEndDate 050..." + order_id);
                                                                                if (err) {
                                                                                    logger.debug("exports.actuaryByStartEndDate 051..." + order_id);
                                                                                    // 错误
                                                                                    tempMtOrderActuaryLog.isError = true;
                                                                                    tempMtOrderActuaryLog.comment = "小区邀请人不是大使订单佣金保存错误";
                                                                                    tempMtOrderActuaryLog.save(function (saveErr, saveResult) {
                                                                                        callbackEachSeriesInner(false);
                                                                                    });
                                                                                } else {
                                                                                    logger.debug("exports.actuaryByStartEndDate 052..." + order_id);
                                                                                    // 保存数据
                                                                                    logger.info(updateResult);
                                                                                    tempMtOrderActuaryLog.isError = false;
                                                                                    tempMtOrderActuaryLog.comment = "小区邀请人不是大使订单佣金保存正确";
                                                                                    tempMtOrderActuaryLog.save(function (saveErr, saveResult) {
                                                                                        callbackEachSeriesInner(false);
                                                                                    });
                                                                                }
                                                                            });
                                                                        }
                                                                    });
                                                                } else {
                                                                    logger.debug("exports.actuaryByStartEndDate 053..." + order_id);
                                                                    // 当前小区无大使
                                                                    saveOrder.comment = "下单人所在小区无大使,前三项佣金无人得到！";
                                                                    logger.debug("下单人所在小区无大使,前三项佣金无人得到！");
                                                                    mtOrder.update(option, saveOrder).exec(function (err, updateResult) {
                                                                        logger.debug("exports.actuaryByStartEndDate 054..." + order_id);
                                                                        if (err) {
                                                                            logger.debug("exports.actuaryByStartEndDate 055..." + order_id);
                                                                            // 错误
                                                                            tempMtOrderActuaryLog.isError = true;
                                                                            tempMtOrderActuaryLog.comment = "下单人所在小区无大使保存错误";
                                                                            tempMtOrderActuaryLog.save(function (saveErr, saveResult) {
                                                                                callbackEachSeriesInner(false);
                                                                            });
                                                                        } else {
                                                                            logger.debug("exports.actuaryByStartEndDate 056..." + order_id);
                                                                            // 保存数据
                                                                            logger.info(updateResult);
                                                                            tempMtOrderActuaryLog.isError = false;
                                                                            tempMtOrderActuaryLog.comment = "下单人所在小区无大使保存正常";
                                                                            tempMtOrderActuaryLog.save(function (saveErr, saveResult) {
                                                                                callbackEachSeriesInner(false);
                                                                            });
                                                                        }
                                                                    });
                                                                }
                                                            })
                                                        } else {
                                                            logger.debug("exports.actuaryByStartEndDate 057..." + order_id);
                                                            saveOrder.comment = "下单人没有小区！";
                                                            logger.error("下单人没有小区！");
                                                            mtOrder.update(option, saveOrder).exec(function (err, updateResult) {
                                                                logger.debug("exports.actuaryByStartEndDate 058..." + order_id);
                                                                if (err) {
                                                                    logger.debug("exports.actuaryByStartEndDate 059..." + order_id);
                                                                    // 错误
                                                                    tempMtOrderActuaryLog.isError = true;
                                                                    tempMtOrderActuaryLog.comment = "下单人没有小区保存错误";
                                                                    tempMtOrderActuaryLog.save(function (saveErr, saveResult) {
                                                                        callbackEachSeriesInner(false);
                                                                    });
                                                                } else {
                                                                    logger.debug("exports.actuaryByStartEndDate 060..." + order_id);
                                                                    // 保存数据
                                                                    logger.info(updateResult);
                                                                    tempMtOrderActuaryLog.isError = false;
                                                                    tempMtOrderActuaryLog.comment = "下单人没有小区保存正常";
                                                                    tempMtOrderActuaryLog.save(function (saveErr, saveResult) {
                                                                        callbackEachSeriesInner(false);
                                                                    });
                                                                }
                                                            });
                                                        }
                                                    });
                                                }
                                            });
                                        }
                                    });
                                // } else {
                                //     logger.debug("exports.actuaryByStartEndDate 061..." + order_id);
                                //     saveOrder.shareCommission = 0; // 分享订单佣金
                                //     saveOrder.shareCommissionUser = null; // 分享订单佣金归属
                                //     saveOrder.selfPurchase = 0; // 自购订单佣金
                                //     saveOrder.selfPurchaseUser = null; // 自购订单佣金归属
                                //     saveOrder.communityCommission = 0; // 小区订单佣金
                                //     saveOrder.communityCommissionUser = null; // 小区订单佣金归属
                                //     saveOrder.inviterCommission = 0; // 邀请人佣金
                                //     saveOrder.inviterCommissionUser = null; // 邀请人佣金归属
                                //     saveOrder.comment = "非支付状态";
                                //     logger.debug("非支付状态！");
                                //     mtOrder.update(option, saveOrder).exec(function (err, updateResult) {
                                //         logger.debug("exports.actuaryByStartEndDate 062..." + order_id);
                                //         if (err) {
                                //             logger.debug("exports.actuaryByStartEndDate 063..." + order_id);
                                //             // 错误
                                //             tempMtOrderActuaryLog.isError = true;
                                //             tempMtOrderActuaryLog.comment = "非支付状态保存错误";
                                //             tempMtOrderActuaryLog.save(function (saveErr, saveResult) {
                                //                 callbackEachSeriesInner(false);
                                //             });
                                //         } else {
                                //             logger.debug("exports.actuaryByStartEndDate 064..." + order_id);
                                //             // 保存数据
                                //             logger.info(updateResult);
                                //             tempMtOrderActuaryLog.isError = false;
                                //             tempMtOrderActuaryLog.comment = "非支付状态保存正确";
                                //             tempMtOrderActuaryLog.save(function (saveErr, saveResult) {
                                //                 callbackEachSeriesInner(false);
                                //             });
                                //         }
                                //     });
                                // }
                            }, function (err) {
                                callbackSkipCountInner(false);
                            });
                        } else {
                            callbackSkipCountInner(false);
                        }
                    });
            }, function (err5) {
                logger.debug('执行完成...');
                callback();
            });
        }
    });
};

// 手动同步小区大使业绩信息（区间）
exports.getMtOrderByStartEndDateFromTo = function (fromDateSelect, toDateSelect, callback) {
    var fromToArray = toolUtil.getArrayDateByStartEndDateMin(fromDateSelect, toDateSelect);
    var allCount = 0;

    var days = actuaryBeforeDays;
    var dayBeforeNend = new Date(moment(moment().format('YYYY-MM-DD')).subtract(days, "days").subtract(1, "seconds").format("YYYY-MM-DD hh:mm:ss a"));
    // var dayBeforeNstart = new Date(moment(moment().format('YYYY-MM-DD')).subtract(days + 1, "days").format("YYYY-MM-DD hh:mm:ss a"));

    async.eachSeries(fromToArray, function (tempDate, callbackTempInner) {
        var today = new Date(moment(tempDate, "YYYY-MM-DD").format());
        var tomorrow = new Date(moment(tempDate, "YYYY-MM-DD").add(1, "days").subtract(1, 'seconds').format("YYYY-MM-DD hh:mm:ss a"));
        logger.info('手动粗算或精算订单时间范围，exports.getMtOrderByStartEndDateFromTo参数为: ' + moment(today).format('YYYY-MM-DD HH:mm:ss') + ',' + moment(tomorrow).format('YYYY-MM-DD HH:mm:ss'));
        var flag = null;
        if(dayBeforeNend.getTime() < today.getTime()) {
            // 粗算
            flag = 1;
            logger.debug("当天进行粗算...");
        } else {
            // 精算
            flag = 2;
            logger.debug("当天进行精算...");
        }
        async.series([
            function(callbackSeriesInner) {
                exports.getMtOrderByStartEndDate(today.getTime(), tomorrow.getTime(), today, tomorrow, 1, null, null, function(err, tempCount) {
                    allCount += tempCount;
                    if(err) {
                        logger.info('同步失败...' + err);
                    } else {
                        logger.info('成功执行...' + tempCount);
                    }
                    callbackSeriesInner();
                });
            },
            function(callbackSeriesInner) {
                exports.getMtOrderByStartEndDate(today.getTime(), tomorrow.getTime(), today, tomorrow, 1, null, null, function(err, tempCount) {
                    if(err) {
                        logger.info('同步失败...' + err);
                    } else {
                        logger.info('成功执行...' + tempCount);
                    }
                    callbackSeriesInner();
                });
            },
            function(callbackInner) {
                // 前15天数据(不会在变化)进行复核
                exports.getNextVersionByDbName("mt_order_check_log", function(err, version){
                    exports.getMtOrderByStartEndDate(today.getTime(), tomorrow.getTime(), today, tomorrow, 2, version, true, function(err, totalCount) {
                        if(err) {
                            logger.info('复核失败...' + err);
                            callbackInner(null, "error");
                        } else {
                            logger.info('复核成功执行件数...' + totalCount);
                            callbackInner(null, "success");
                        }
                    });
                });
            },

            // 同步退款单
            function(callbackInner) {
                // 66订单退款状态
                exports.refundStatusFor66OneDay(today, tomorrow, function(err, totalCount) {
                    if(err) {
                        logger.info('同步退款信息失败...' + err);
                        callbackInner(null, "error");
                    } else {
                        logger.info('同步退款信息成功执行件数...' + totalCount);
                        callbackInner(null, "success");
                    }
                });
            },

            // 精算
            function(callbackInner) {
                exports.getNextVersionByDbName("mt_order_actuary_log", function(err, version){
                    exports.actuaryByStartEndDate(today, tomorrow, flag, version, false, function (err, status) {
                        if(err) {
                            logger.info('同步失败...' + err);
                        } else {
                            logger.info('成功执行...' + allCount);
                        }
                        callbackInner(false);
                    });
                });
            }
        ], function(err, result) {
            callbackTempInner(false);
        });

    }, function (tempErr) {
        callback(null, allCount);
    });
};

// 粗算
exports.getMtOrderByStartEndDateFromToRough = function (fromDateSelect, toDateSelect, callback) {
    var fromToArray = toolUtil.getArrayDateByStartEndDateMin(fromDateSelect, toDateSelect);
    var allCount = fromToArray.length;
    exports.getNextVersionByDbName("mt_order_actuary_log", function(err, version){
        async.eachSeries(fromToArray, function (tempDate, callbackTempInner) {
            var dayBeforeNstart = new Date(moment(tempDate, "YYYY-MM-DD").format());
            var dayBeforeNend = new Date(moment(tempDate, "YYYY-MM-DD").add(1, "days").subtract(1, 'seconds').format("YYYY-MM-DD hh:mm:ss a"));
            exports.actuaryByStartEndDate(dayBeforeNstart, dayBeforeNend, 1, version, false, function (err, status) {
                if(err) {
                    logger.info('同步失败...' + err);
                } else {
                    logger.info('成功执行...' + allCount);
                }
                callbackTempInner(false);
            });
        }, function (tempErr) {
            callback(null, allCount);
        });
    });
};

// 复核
exports.getMtOrderByStartEndDateFromToCheck = function (fromDateSelect, toDateSelect, callback) {
    var fromToArray = toolUtil.getArrayDateByStartEndDateMin(fromDateSelect, toDateSelect);
    var allCount = 0;
    exports.getNextVersionByDbName("mt_order_check_log", function(err, version){
        async.eachSeries(fromToArray, function (tempDate, callbackTempInner) {
            var today = new Date(moment(tempDate, "YYYY-MM-DD").format());
            var tomorrow = new Date(moment(tempDate, "YYYY-MM-DD").add(1, "days").subtract(1, 'seconds').format("YYYY-MM-DD hh:mm:ss a"));
                exports.getMtOrderByStartEndDate(today.getTime(), tomorrow.getTime(), today, tomorrow, 2, version, false, function(err, tempCount) {
                    allCount += tempCount;
                    if(err) {
                        logger.info('同步失败...' + err);
                    } else {
                        logger.info('成功执行...' + tempCount);
                    }
                    callbackTempInner(false);
                });
        }, function (tempErr) {
            callback(null, allCount);
        });
    });
};

// 精算
exports.getMtOrderByStartEndDateFromToActuary = function (fromDateSelect, toDateSelect, callback) {
    var days = actuaryBeforeDays;
    var dayBeforeNendTemp = new Date(moment(moment().format('YYYY-MM-DD')).subtract(days, "days").subtract(1, "seconds").format("YYYY-MM-DD hh:mm:ss a"));
    logger.info('手动粗算或精算订单时间范围，exports.getMtOrderByStartEndDateFromTo参数为: ' + moment(fromDateSelect).format('YYYY-MM-DD HH:mm:ss') + ',' + moment(toDateSelect).format('YYYY-MM-DD HH:mm:ss'));
    var fromToArray = toolUtil.getArrayDateByStartEndDateMin(fromDateSelect, toDateSelect);
    var allCount = fromToArray.length;
    var flag = null;
    exports.getNextVersionByDbName("mt_order_actuary_log", function(err, version){
        async.eachSeries(fromToArray, function (tempDate, callbackTempInner) {
            var dayBeforeNstart = new Date(moment(tempDate, "YYYY-MM-DD").format());
            var dayBeforeNend = new Date(moment(tempDate, "YYYY-MM-DD").add(1, "days").subtract(1, 'seconds').format("YYYY-MM-DD hh:mm:ss a"));
            if(dayBeforeNendTemp.getTime() < dayBeforeNstart.getTime()) {
                // 粗算
                flag = 1;
                logger.debug("当天进行粗算...");
            } else {
                // 精算
                flag = 2;
                logger.debug("当天进行精算...");
            }
            exports.actuaryByStartEndDate(dayBeforeNstart, dayBeforeNend, flag, version, false, function (err, status) {
                if(err) {
                    logger.info('同步失败...' + err);
                } else {
                    logger.info('成功执行...' + allCount);
                }
                callbackTempInner(false);
            });
        }, function (tempErr) {
            callback(null, allCount);
        });
    });
};

// 取得最新版本号+1
exports.getNextVersionByDbName = function (dbName, callback) {
    var versionPre = moment().format('YYYYMMDD');
    var version = versionPre + "" + "001";
    if(dbName == "mt_order_check_log") {
        mtOrderCheckLog.findOne({"version": {$gte : version}}, function (err, tempData) {
            if(err) {
                callback(null, version);
            } else {
                if(tempData) {
                    callback(null, tempData.version + 1);
                } else {
                    callback(null, version);
                }
            }
        });
    } else if(dbName == "mt_order_actuary_log") {
        mtOrderActuaryLog.findOne({"version": {$gte : version}}, function (err, tempData) {
            if(err) {
                callback(null, version);
            } else {
                if(tempData) {
                    callback(null, tempData.version + 1);
                } else {
                    callback(null, version);
                }
            }
        });
    } else {
        callback(null, version);
    }
};

exports.getMtOrderByStartEndDate = function (starttime, endtime, startmoment, endmoment, flag, version, autoFlag, callback) {
    // >= startDate < endDate
    try{
        var mtUrl = mtOrderUrl;
        var param = '?platform=8&signature=none&timestamp=' + moment().format('YYYYMMDDhhmmss');
        var pageno = 1;
        var pagesize = 100;
        var signtime = new Date().getTime();
            var params = toolUtil.getMtSignParams(starttime, endtime, pageno, pagesize, signtime);
            var finalUrl = mtUrl + param + params;
            logger.info(finalUrl);
            restClient.get(finalUrl, function (tempData, response) {
                logger.info('取得美囤订单返回状态值:' + response.statusCode);
                if (response.statusCode == 200 && tempData != null && tempData != 'unknown') {
                    // 美囤上线后使用
                    var returnData = JSON.parse(tempData);
                    // 临时用,美囤上线后不再使用
                    // var returnData = JSON.parse(tempData.toString().replace(/:\s\d{17}/g, ":\"@!#@!#$&\"").replace(/:\d{17}/g, ":\"@!#@!#$&\"").replace(/@!#@!#:\s/g,"").replace(/@!#@!#:/g,""))
                    var rtn_code = returnData.rtn_code;
                    logger.info('rtn_code:' + rtn_code);
                    if(rtn_code == '0') {
                        logger.info('rtn_code=0');
                        pageno++;
                        var data = returnData.data;
                        var totalPageCount = data.totalPageCount;
                        var totalCount = data.totalCount;
                        var list = data.list;
                        logger.debug('exports.compareAndSaveMtOrder start...');
                        logger.debug('totalCount...' + totalCount);
                        if (list && list.length > 0) {
                            if (flag == 1) {
                                exports.compareAndSaveMtOrder(list);
                            } else if (flag == 2) {
                                exports.checkMtOrderByStartEndDate(list, version, autoFlag);
                            }
                        }
                        logger.debug('exports.compareAndSaveMtOrder end...');

                        logger.info('totalPageCount:' + totalPageCount);
                        if(totalPageCount >= 2) {
                            for(var i= 2; i <= totalPageCount; i++) {
                                var innerParams = toolUtil.getMtSignParams(starttime, endtime, i, pagesize, signtime);
                                var innerFinalUrl = mtUrl + param + innerParams;
                                logger.info(innerFinalUrl);
                                restClient.get(innerFinalUrl, function (innerTempData, innerResponse) {
                                    logger.info('inner取得美囤订单返回状态值:' + innerResponse.statusCode);
                                    if (innerResponse.statusCode == 200 && innerTempData != null && innerTempData != 'unknown') {
                                        // 美囤上线后使用
                                        var innerReturnData = JSON.parse(innerTempData);
                                        // 临时用,美囤上线后不再使用
                                        // var innerReturnData = JSON.parse(innerTempData.toString().replace(/:\s\d{17}/g, ":\"@!#@!#$&\"").replace(/:\d{17}/g, ":\"@!#@!#$&\"").replace(/@!#@!#:\s/g,"").replace(/@!#@!#:/g,""))
                                        var innerRtnCode = innerReturnData.rtn_code;
                                        logger.info('inner rtn_code:' + innerRtnCode);
                                        if(innerRtnCode == '0') {
                                            pageno++;
                                            var innerData = innerReturnData.data;
                                            var innerList = innerData.list;
                                            if(innerList && innerList.length > 0) {
                                                if(flag == 1) {
                                                    exports.compareAndSaveMtOrder(innerList);
                                                } else if(flag == 2) {
                                                    exports.checkMtOrderByStartEndDate(innerList, version, autoFlag);
                                                }
                                            }
                                            logger.info('current pageno:' + pageno);
                                            if(pageno > totalPageCount) {
                                                // 正常同步N条(N>=2)
                                                var regionOption = {'order_time': {$gte: startmoment, $lte: endmoment}};
                                                logger.debug(regionOption);
                                                mtOrder.count(regionOption, function(mtOrderErr, mtOrderCount) {
                                                    if(mtOrderErr) {
                                                        logger.error(mtOrderErr);
                                                    }
                                                    logger.info('mongodb的mtOrder.count参数为: ' + moment(startmoment).format('YYYY-MM-DD HH:mm:ss') + ',' + moment(endmoment).format('YYYY-MM-DD HH:mm:ss'));
                                                    logger.info('当前区间内mongodb取得件数为...' + mtOrderCount);
                                                    if(totalCount == mtOrderCount) {
                                                        logger.info('当前区间内mongodb取得件数与meitun取得件数一致...' + mtOrderCount);
                                                    } else {
                                                        logger.error('当前区间内mongodb取得件数与meitun取得件数不一致...');
                                                        logger.error('mongodb取得件数...' + mtOrderCount + ',meitun取得件数...' + totalCount);
                                                    }
                                                });
                                                callback(null, totalCount);
                                            }
                                        } else {
                                            // 失败则重试
                                            logger.error(innerReturnData.rtn_msg);
                                            logger.error(innerReturnData);
                                            callback(null, null);
                                        }
                                    } else {
                                        // 失败则重试
                                        callback(null, null);
                                    }
                                }).on('error', function (err) {
                                    // 失败则重试
                                    callback(null, null);
                                });
                            }
                        } else {
                            // 正常同步1条
                            // 正常同步N条(N>=2)
                            var regionOption = {'order_time': {$gte: startmoment, $lte: endmoment}};
                            logger.debug(regionOption);
                            mtOrder.count(regionOption, function(mtOrderErr, mtOrderCount) {
                                if(mtOrderErr) {
                                    logger.error(mtOrderErr);
                                }
                                logger.info('mongodb的mtOrder.count参数为: ' + moment(startmoment).format('YYYY-MM-DD HH:mm:ss') + ',' + moment(endmoment).format('YYYY-MM-DD HH:mm:ss'));
                                logger.info('当前区间内mongodb取得件数为...' + mtOrderCount);
                                if(totalCount == mtOrderCount) {
                                    logger.info('当前区间内mongodb取得件数与meitun取得件数一致...' + mtOrderCount);
                                } else {
                                    logger.error('当前区间内mongodb取得件数与meitun取得件数不一致...');
                                    logger.error('mongodb取得件数...' + mtOrderCount + ',meitun取得件数...' + totalCount);
                                }
                            });
                            callback(null, totalCount);
                        }
                    } else {
                        logger.error('rtn_code!=0');
                        logger.error(returnData.rtn_msg);
                        logger.error(returnData);
                        // 失败则重试
                        callback(null, null);
                    }
                } else {
                    // 失败则重试
                    callback(null, null);
                }
        }).on('error', function (err) {
            // 失败则重试
            callback(null, null);
        });
    } catch(e) {
        logger.error(e);
        callback(e, null);
    }
};

// 保存数据
exports.compareAndSaveMtOrder = function (orderList) {
    logger.info('compareAndSaveMtOrder start...');
    async.eachSeries(orderList, function (row, callbackInner) {
        var order_id = row.id; // 订单id
        var temp_order_time = row.createTime; // 下单时间(time类型)
        var order_time = moment(new Date(temp_order_time)).format("YYYY-MM-DD HH:mm:ss");
        var sku_code = row.skuCode;

        var tempModifyTime = row.modifyTime; // 订单状态变更时间
        var modifyTime = moment(new Date(tempModifyTime)).format("YYYY-MM-DD HH:mm:ss");

        // balanceStatus : {type: Number, default: 0}, // 结算状态 1:已粗算，2:已精算，3:本单结算，4:提成结算，5::全部结算，0:初始值（4种）
        var option = {'order_id': order_id, 'sku_code': sku_code, 'balanceStatus': {'$in' : [0, 1, 2]}};
        logger.debug(option);
        mtOrder.count(option, function(err, tempCount) {
            // 如果不存在，则保存
            if(tempCount == 0) {
                var spuName = row.spuName;
                var uhp = row.uhp;
                var shareUhp = row.shareUhp;
                var itemSaleType = row.itemSaleType;
                //是否海淘商品,1-否，2-是，默认1
                var wavesSign = row.wavesSign;
                //是否标品 0 非标品  1标品  -1未设置
                var standard = row.standard;

                var tempMtOrder = new mtOrder();
                tempMtOrder.order_id = order_id; // 订单id
                tempMtOrder.member_id = row.memberId; // 美囤id
                tempMtOrder.order_uid = row.uid; // 宝宝树id
                tempMtOrder.order_uhp = uhp; // 手机号
                tempMtOrder.share_uid = row.shareUid; // 分享人宝宝树id
                tempMtOrder.share_uhp = shareUhp; // 分享人手机号
                tempMtOrder.modifyTime = modifyTime; // 订单状态变更时间
                tempMtOrder.price = row.price; // 单价(拼团活动价)
                tempMtOrder.total = row.total; // 总价格
                tempMtOrder.sku_code = row.skuCode; // 商品编码
                tempMtOrder.sku_name = spuName; // 品名
                tempMtOrder.quantity = row.quantity; // 数量
                tempMtOrder.skuQuantity = row.skuQuantity; // sku购买数量
                tempMtOrder.skuSubTotal = row.skuSubTotal; // sku优惠后总价
                tempMtOrder.order_time = order_time; // 下单时间

                <!--  宝宝树66小区六次改造 自营非自营 mod   guo.xiaomin  20171222  start   -->
                if(toolUtil.isNotEmpty(itemSaleType)) {
                    tempMtOrder.originalItemSaleType = itemSaleType;
                }
                var tempItemSaleType = itemSaleType;
                if(spuName.indexOf("宝宝树专定") != -1) {
                    tempItemSaleType = 0; //销售类型 0-自营 1-非自营
                }
                tempMtOrder.itemSaleType = tempItemSaleType;
                <!--  宝宝树66小区六次改造 自营非自营 mod   guo.xiaomin  20171222  end   -->



                if(toolUtil.isNotEmpty(wavesSign)) {
                    tempMtOrder.wavesSign = wavesSign;
                }
                <!--  宝宝树66小区五次改造 拼团新列追加 mod   guo.xiaomin  20171129  start   -->
                if(toolUtil.isNotEmpty(standard)) {
                    tempMtOrder.originalStandard = standard;
                }

                var tempStandard = null;
                var largeId = row.largeId;
                var mediumId = row.mediumId;
                var smallId = row.smallId;
                // 大分类
                if(toolUtil.isNotEmpty(largeId)) {
                    tempMtOrder.largeId = largeId;
                    if(skuLargeId) {
                        if(skuLargeId.indexOf(largeId) != -1) {
                            tempStandard = 1; // 标品
                        } else {
                            tempStandard = 0; // 非标品
                        }
                    } else {
                        logger.error("OPM配置参数没有:global.skuLargeId");
                    }
                }
                tempMtOrder.standard = tempStandard;
                // 中分类
                if(toolUtil.isNotEmpty(mediumId)) {
                    tempMtOrder.mediumId = mediumId;
                }
                // 小分类
                if(toolUtil.isNotEmpty(smallId)) {
                    tempMtOrder.smallId = smallId;
                }
                <!--  宝宝树66小区五次改造 拼团新列追加 mod   guo.xiaomin  20171129  end   -->

                <!--  宝宝树66小区三次改造 拼团新列追加 mod   guo.xiaomin  20171020  start   -->
                //订单类型（1：普通  2：海淘 5：拼团）
                var orderType = row.orderType;
                tempMtOrder.orderType = orderType;

                // 是否是新版本拼团订单 0-否;1-是
                var isNewGroupOrder = row.isNewGroupOrder;
                tempMtOrder.isNewGroupOrder = isNewGroupOrder;
                if(isNewGroupOrder == 1) {
                    // isNewGroupOrder="1"时  才有以下字段
                    // 新版本拼团状态 0-已成团;1-未成团;2-待成团;3-已抢光
                    var newGroupOrderStatus = row.newGroupOrderStatus;
                    //拼团活动id(数字)
                    var promotionId = row.promotionId;
                    //拼团实例code(字符串)
                    var proBizCode = row.proBizCode;

                    tempMtOrder.newGroupOrderStatus = newGroupOrderStatus;
                    tempMtOrder.promotionId = promotionId;
                    tempMtOrder.proBizCode = proBizCode;
                }
                <!--  宝宝树66小区三次改造 拼团新列追加 mod    guo.xiaomin  20171020  end   -->

                if(toolUtil.isNotEmpty(row.status)) {
                    tempMtOrder.status = row.status;
                }
                if(toolUtil.isNotEmpty(row.doneTime)) {
                    tempMtOrder.doneTime = moment(new Date(row.doneTime)).format("YYYY-MM-DD HH:mm:ss");
                }
                if(toolUtil.isNotEmpty(row.refundStatus)) {
                    tempMtOrder.refundStatus = row.refundStatus;
                }
                if(toolUtil.isNotEmpty(row.refundTime)) {
                    tempMtOrder.refundTime = moment(new Date(row.refundTime)).format("YYYY-MM-DD HH:mm:ss");
                }

                async.parallel([
                    function(callbackInnerInner) {
                        // 下单人是否是小区大使
                        if(uhp) {
                            userService.isModeratorManager(uhp, function (err, tempResult) {
                                tempMtOrder.is_order_moderator = tempResult;
                                callbackInnerInner(null, tempResult);
                            });
                        } else {
                            callbackInnerInner(null, false);
                        }
                    },
                    function(callbackInnerInner) {
                        // 分享人是否是小区大使
                        if(shareUhp) {
                            userService.isModeratorManager(shareUhp, function (err, tempResult) {
                                tempMtOrder.is_share_moderator = tempResult;
                                callbackInnerInner(null, tempResult);
                            });
                        } else {
                            callbackInnerInner(null, false);
                        }
                    },
                    function(callbackInnerInner) {
                        // 下单人是否是小区大使
                        if(uhp) {
                            userService.getUserIdByMobilePhone(uhp, function (err, tempResult) {
                                tempMtOrder.order_user = tempResult;
                                callbackInnerInner(null, tempResult);
                            });
                        } else {
                            callbackInnerInner(null, false);
                        }
                    },
                    function(callbackInnerInner) {
                        // 分享人是否是小区大使
                        if(shareUhp) {
                            userService.getUserIdByMobilePhone(shareUhp, function (err, tempResult) {
                                tempMtOrder.share_user = tempResult;
                                callbackInnerInner(null, tempResult);
                            });
                        } else {
                            callbackInnerInner(null, false);
                        }
                    }
                ], function(err, parallelResult) {
                    tempMtOrder.save(function (err, updateResult) {
                        callbackInner(false);
                    });
                });

            } else {
                var spuName = row.spuName;
                var tempMtOrder = {};
                tempMtOrder.dateLastModified = new Date(); // 最后更新时间
                var uhp = row.uhp;
                var shareUhp = row.shareUhp;
                var itemSaleType = row.itemSaleType;
                var wavesSign = row.wavesSign;
                var standard = row.standard;
                tempMtOrder.order_time = new Date(order_time);
                if(toolUtil.isNotEmpty(row.memberId)) {
                    tempMtOrder.member_id = row.memberId; // 美囤id
                } else {
                    tempMtOrder.member_id = null;
                }
                if(toolUtil.isNotEmpty(row.uid)) {
                    tempMtOrder.order_uid = row.uid; // 宝宝树id
                } else {
                    tempMtOrder.order_uid = null;
                }
                if(toolUtil.isNotEmpty(uhp)) {
                    tempMtOrder.order_uhp = uhp; // 手机号
                } else {
                    tempMtOrder.order_uhp = null;
                }
                if(toolUtil.isNotEmpty(row.shareUid)) {
                    tempMtOrder.share_uid = row.shareUid; // 分享人宝宝树id
                } else {
                    tempMtOrder.share_uid = null;
                }
                if(toolUtil.isNotEmpty(shareUhp)) {
                    tempMtOrder.share_uhp = shareUhp; // 分享人手机号
                } else {
                    tempMtOrder.share_uhp = null;
                }
                if(toolUtil.isNotEmpty(row.price)) {
                    tempMtOrder.price = row.price; // 价格
                } else {
                    tempMtOrder.price = null; // 价格
                }
                if(toolUtil.isNotEmpty(row.total)) {
                    tempMtOrder.total = row.total; // 总价格
                } else {
                    tempMtOrder.total = null; // 总价格
                }
                if(toolUtil.isNotEmpty(row.skuCode)) {
                    tempMtOrder.sku_code = row.skuCode; // 商品编码
                } else {
                    tempMtOrder.sku_code = null; // 商品编码
                }
                if(toolUtil.isNotEmpty(row.spuName)) {
                    tempMtOrder.sku_name = row.spuName; // 品名
                } else {
                    tempMtOrder.sku_name = null; // 品名
                }
                if(toolUtil.isNotEmpty(row.quantity)) {
                    tempMtOrder.quantity = row.quantity; // 数量
                } else {
                    tempMtOrder.quantity = null; // 数量
                }
                if(toolUtil.isNotEmpty(row.skuQuantity)) {
                    tempMtOrder.skuQuantity = row.skuQuantity; // sku购买数量
                } else {
                    tempMtOrder.skuQuantity = null; // sku购买数量
                }
                if(toolUtil.isNotEmpty(row.skuSubTotal)) {
                    tempMtOrder.skuSubTotal = row.skuSubTotal;  // sku优惠后总价
                } else {
                    tempMtOrder.skuSubTotal = null;  // sku优惠后总价
                }

                <!--  宝宝树66小区六次改造 自营非自营 mod   guo.xiaomin  20171222  start   -->
                // if(toolUtil.isNotEmpty(itemSaleType)) {
                //     tempMtOrder.itemSaleType = itemSaleType;
                // } else {
                //     tempMtOrder.itemSaleType = null;
                // }
                if(toolUtil.isNotEmpty(itemSaleType)) {
                    tempMtOrder.originalItemSaleType = itemSaleType;
                } else {
                    tempMtOrder.originalItemSaleType = null;
                }
                var tempItemSaleType = itemSaleType;
                if(spuName.indexOf("宝宝树专定") != -1) {
                    tempItemSaleType = 0; //销售类型 0-自营 1-非自营
                }
                if(toolUtil.isNotEmpty(tempItemSaleType)) {
                    tempMtOrder.itemSaleType = tempItemSaleType;
                } else {
                    tempMtOrder.itemSaleType = null;
                }
                <!--  宝宝树66小区六次改造 自营非自营 mod   guo.xiaomin  20171222  end   -->

                if(toolUtil.isNotEmpty(wavesSign)) {
                    tempMtOrder.wavesSign = wavesSign;
                } else {
                    tempMtOrder.wavesSign = null;
                }

                <!--  宝宝树66小区五次改造 拼团新列追加 mod   guo.xiaomin  20171129  start   -->
                // if(toolUtil.isNotEmpty(standard)) {
                //     tempMtOrder.standard = standard;
                // } else {
                //     tempMtOrder.standard = null;
                // }

                var tempStandard = null;

                var largeId = row.largeId;
                var mediumId = row.mediumId;
                var smallId = row.smallId;
                // 大分类
                if(toolUtil.isNotEmpty(largeId)) {
                    tempMtOrder.largeId = largeId;
                    if(skuLargeId) {
                        if(skuLargeId.indexOf(largeId) != -1) {
                            tempStandard = 1; // 标品
                        } else {
                            tempStandard = 0; // 非标品
                        }
                    } else {
                        logger.error("OPM配置参数没有:global.skuLargeId");
                    }
                } else {
                    tempMtOrder.largeId = null;
                }
                tempMtOrder.standard = tempStandard;
                // 中分类
                if(toolUtil.isNotEmpty(mediumId)) {
                    tempMtOrder.mediumId = mediumId;
                } else {
                    tempMtOrder.mediumId = null;
                }
                // 小分类
                if(toolUtil.isNotEmpty(smallId)) {
                    tempMtOrder.smallId = smallId;
                } else {
                    tempMtOrder.smallId = null;
                }
                <!--  宝宝树66小区五次改造 拼团新列追加 mod   guo.xiaomin  20171129  end   -->

                if(toolUtil.isNotEmpty(row.orderType)) {
                    tempMtOrder.orderType = row.orderType;
                } else {
                    tempMtOrder.orderType = null;
                }
                var isNewGroupOrder = row.isNewGroupOrder;
                if(toolUtil.isNotEmpty(isNewGroupOrder)) {
                    tempMtOrder.isNewGroupOrder = isNewGroupOrder;
                } else {
                    tempMtOrder.isNewGroupOrder = null;
                }
                if(isNewGroupOrder == 1) {
                    // isNewGroupOrder="1"时  才有以下字段
                    // 新版本拼团状态 0-已成团;1-未成团;2-待成团;3-已抢光
                    var newGroupOrderStatus = row.newGroupOrderStatus;
                    //拼团活动id(数字)
                    var promotionId = row.promotionId;
                    //拼团实例code(字符串)
                    var proBizCode = row.proBizCode;
                    if(toolUtil.isNotEmpty(newGroupOrderStatus)) {
                        tempMtOrder.newGroupOrderStatus = newGroupOrderStatus;
                    } else {
                        tempMtOrder.newGroupOrderStatus = null;
                    }
                    if(toolUtil.isNotEmpty(promotionId)) {
                        tempMtOrder.promotionId = promotionId;
                    } else {
                        tempMtOrder.promotionId = null;
                    }
                    if(toolUtil.isNotEmpty(proBizCode)) {
                        tempMtOrder.proBizCode = proBizCode;
                    } else {
                        tempMtOrder.proBizCode = null;
                    }
                } else {
                    tempMtOrder.newGroupOrderStatus = null;
                    tempMtOrder.promotionId = null;
                    tempMtOrder.proBizCode = null;
                }
                if(toolUtil.isNotEmpty(row.status)) {
                    tempMtOrder.status = row.status;
                } else {
                    tempMtOrder.status = null;
                }
                if(toolUtil.isNotEmpty(row.doneTime)) {
                    tempMtOrder.doneTime = moment(new Date(row.doneTime)).format("YYYY-MM-DD HH:mm:ss");
                } else {
                    tempMtOrder.doneTime = null;
                }
                if(toolUtil.isNotEmpty(row.refundStatus)) {
                    tempMtOrder.refundStatus = row.refundStatus;
                } else {
                    tempMtOrder.refundStatus = null;
                }
                if(toolUtil.isNotEmpty(row.refundTime)) {
                    tempMtOrder.refundTime = moment(new Date(row.refundTime)).format("YYYY-MM-DD HH:mm:ss");
                } else {
                    tempMtOrder.refundTime = null;
                }
                if(toolUtil.isNotEmpty(row.modifyTime)) { // 订单状态变更时间
                    tempMtOrder.modifyTime = moment(new Date(row.modifyTime)).format("YYYY-MM-DD HH:mm:ss");
                } else {
                    tempMtOrder.modifyTime = null;
                }

                async.parallel([
                    function(callbackInnerInner) {
                        // 下单人是否是小区大使
                        if(uhp) {
                            userService.isModeratorManager(uhp, function (err, tempResult) {
                                tempMtOrder.is_order_moderator = tempResult;
                                callbackInnerInner(null, tempResult);
                            });
                        } else {
                            callbackInnerInner(null, false);
                        }
                    },
                    function(callbackInnerInner) {
                        // 分享人是否是小区大使
                        if(shareUhp) {
                            userService.isModeratorManager(shareUhp, function (err, tempResult) {
                                tempMtOrder.is_share_moderator = tempResult;
                                callbackInnerInner(null, tempResult);
                            });
                        } else {
                            callbackInnerInner(null, false);
                        }
                    },
                    function(callbackInnerInner) {
                        // 下单人是否是小区大使
                        if(uhp) {
                            userService.getUserIdByMobilePhone(uhp, function (err, tempResult) {
                                tempMtOrder.order_user = tempResult;
                                callbackInnerInner(null, tempResult);
                            });
                        } else {
                            callbackInnerInner(null, false);
                        }
                    },
                    function(callbackInnerInner) {
                        // 分享人是否是小区大使
                        if(shareUhp) {
                            userService.getUserIdByMobilePhone(shareUhp, function (err, tempResult) {
                                tempMtOrder.share_user = tempResult;
                                callbackInnerInner(null, tempResult);
                            });
                        } else {
                            callbackInnerInner(null, false);
                        }
                    }
                ], function(err, parallelResult) {
                    mtOrder.update(option, tempMtOrder).exec(function (err, updateResult) {
                        callbackInner(false);
                    });
                });
            }
        });
    }, function (err) {
        logger.info('compareAndSaveMtOrder end...');
        return true;
    });
};
//页面初始化显示（小区大使业绩）
exports.communityAmbassadordataShow = function (req,callback){

    var body = req.body;
    var page = req.params.page;
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;
    var totalPage = 0;

    var opt={};

    if(body.startdate && body.enddate){
        opt['order_time'] = {$gte: decodeURI(body.startdate + ' 00:00:00'), $lt: decodeURI(body.enddate + ' 23:59:59')};
    }
    opt['isValid'] = true ;
    //if(body.storetype) opt.storetype = body.storetype;

    logger.debug(opt);
    async.series([

        function (callbackInner) {
            mtOrder.count(opt, function (err, count) {
                if (err) {
                    return callbackInner(err, null);
                } else {
                    var temp = {count: count, page: Math.ceil(count/size)};
                    callbackInner(null, temp);
                }
            });
        },
        function (callbackInner) {
            mtOrder.find(opt).skip(index).limit(size).populate('order_user', '_id nickName community cityId encUserId').populate('share_user','_id nickName community cityId encUserId')
                .exec(function (err, results) {
                    if (results == undefined || results == null) {
                        var msg = {
                            "message": 'get err'
                        };
                        callbackInner(msg, null);
                    } else {
                        //callbackInner(null, results);
                        async.eachSeries(results, function (row, callbackTempInner) {
                            var tempdata="";
                            var cityId = "";
                            var community = "";
                            if(row.order_user) {
                                tempdata=row.order_user.community;
                                cityId = row.order_user.cityId;
                                community = row.order_user.community;
                            }
                            /*                            async.series([
                             function (callbackTempInner1){
                             if(!(row.order_user && row.order_user.community)){
                             callbackTempInner1();
                             }else{
                             User.count({
                             "community" : tempdata
                             },function(err,count){
                             row.count=count;
                             callbackTempInner1(err,count);
                             })
                             }
                             },function (callbackTempInner1){
                             if(!(row.order_user && row.order_user.community)){
                             callbackTempInner1();
                             }else{
                             User.find({
                             "community" : tempdata,
                             "userRole" :  4
                             },function(err,user){
                             row.user=user;
                             callbackTempInner1(err,user);
                             })
                             }
                             },function (callbackTempInner1){
                             if(!( row.order_user  &&  row.order_user.cityId)){
                             callbackTempInner1();
                             }else{
                             //购买用户所在城市name
                             Regions.find({
                             "_id" :cityId
                             },function(err,arr){
                             row.city=arr;
                             callbackTempInner1(err,arr);
                             })
                             }
                             },function (callbackTempInner1){
                             if(!(row.order_user && row.order_user.community)){
                             callbackTempInner1();
                             }else{
                             //购买用户所在小区name
                             Community.find({
                             "_id" : community ,
                             },function (err,arr){
                             row.community=arr;
                             callbackTempInner1(err,arr);
                             })
                             }
                             }
                             ],callbackTempInner)*/
                            User.count({
                                "community" : tempdata
                            },function(err,count){
                                row.count=count;
                                User.find({
                                    "community" : tempdata,
                                    "userRole" :  4
                                },function(err,user){
                                    row.user=user;
                                    //购买用户所在城市name
                                    Regions.find({
                                        "_id" :cityId
                                    },function(err,arr){
                                        row.city=arr;
                                        //购买用户所在小区name
                                        Community.find({
                                            "_id" : community ,
                                        },function (err,arr){
                                            row.community=arr;
                                            callbackTempInner(false);
                                        })
                                    })
                                })
                            })

                        },function (tem){
                            callbackInner(null,results);
                        })
                    }
                });
        }
    ], callback);


};



//导出查询数据（小区大使业绩）
exports.communityAmbassadordataExportsData= function (req,callback){

    var body =req.cparams;
    var page = req.params.page;
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;
    var totalPage = 0;

    var opt={};
    opt['order_time'] = {$gte: decodeURI(body.startDate), $lt: decodeURI(body.endDate)};
    opt['isValid'] = true ;

    logger.debug(opt);
    async.series([
        function (callbackInner) {
            mtOrder.count(opt, function (err, count) {
                if (err) {
                    return callbackInner(err, null);
                } else {
                    //var temp = {count: count, page: Math.ceil(count/size)};
                    callbackInner(null);
                }
            });
        },
        function (callbackInner) {
            mtOrder.find(opt).skip(index).limit(size).populate('order_user', '_id nickName community cityId encUserId').populate('share_user','_id nickName community cityId encUserId')
                .exec(function (err, results) {
                    if (results == undefined || results == null) {
                        var msg = {
                            "message": 'get err'
                        };
                        callbackInner(msg, null);
                    } else {
                        //callbackInner(null, results);
                        async.eachSeries(results, function (row, callbackTempInner) {
                            // var tempdata=row.order_user.community.toString();
                            // var cityId = row.order_user.cityId.toString();
                            // var community = row.order_user.community.toString();

                            var tempdata="";
                            var cityId = "";
                            var community = "";
                            if(row.order_user) {
                                tempdata=row.order_user.community;
                                cityId = row.order_user.cityId;
                                community = row.order_user.community;
                            }

                            User.count({
                                "community" :  tempdata
                            },function(err,count){
                                row.count=count;
                                User.find({
                                    "community" : tempdata,
                                    "userRole" :  4
                                },function(err,user){
                                    row.user=user;
                                    //购买用户所在城市name
                                    Regions.find({
                                        "_id" : cityId
                                    },function(err,arr){
                                        row.city=arr;
                                        //购买用户所在小区name
                                        Community.find({
                                            "_id" : community
                                        },function (err,arr){
                                            row.community=arr;
                                            callbackTempInner(false);
                                        })
                                    })
                                })
                            })

                        },function (tem){
                            callbackInner(null,results);
                        })
                    }
                });
        }
    ], callback);
}

//小区大使在APp中查看自己的业绩
exports.communityAmbassadordataShowApp = function (req,callback){
   // var id=req.cparams.id;
   // var id="59a02770f6fd4900000425df";
    var id=req.body.token;
    var  resultArr={};
    async.series([
        function (callbackInner1){
        if(id){
            return callbackInner1(0);
        }else{
            //作为下单人的成单数
            mtOrder.count({
                "order_user" : id
            },function(err,count){
                callbackInner1(null,count);
            })
        }
        },function(callbackInner2){
            if(id){
                return callbackInner2(0);
            }else{
            //作为分享人的成单数
            mtOrder.count({
                "share_user" : id
            },function(err,count){
                callbackInner2(null,count);
            })
        }}
    ],function(innercallback,result){
        countResult=result[0]+result[1];
        resultArr.countResult=countResult;
        callback(null,resultArr);
    });
}
